LoginSignup
8

More than 5 years have passed since last update.

Swift3.0対応 CoreGraphicsで円を描く

Last updated at Posted at 2017-01-10

はじめに

Swift3.0でCoreGraphicsを使った例が少なかったので、簡単なサンプルを作成しました。
塗りつぶしの円とそれに重なる枠線の円を描画しています。

Simulator Screen Shot 2017.01.10 23.21.32.png

塗りつぶしの円の描画

CircleView.swift
private func drawFillCircle(rect: CGRect) {
        // コンテキストの取得(1)
        guard let context = UIGraphicsGetCurrentContext() else {
            return
        }

        // 色の設定(2)
        context.setFillColor(self.fillColor.cgColor)

        // 円を塗りつぶしで描く(3)
        // 円は引数のCGRectに内接する
        context.fillEllipse(in: rect)
    }

(1) コンテキストの取得

コンテキストを取得します。

(2) 描画色の設定

塗りつぶしの色の設定には"setFillColor"を使用します。
引数にはCGColorを指定します。
サンプルではStoryboardで設定した色を引数に渡しています。

(3) 塗りつぶしの円の描画

塗りつぶしの円は"fillEllipse"で描画できます。
引数に指定したCGRectに内接する円が描かれます。

枠線の円の描画

CircleView.swift
private func drawStrokeCircle(rect: CGRect) {
        // コンテキストの取得(1)
        guard let context = UIGraphicsGetCurrentContext() else {
            return
        }

        // 色の設定(2)
        context.setStrokeColor(self.strokeColor.cgColor)

        // 枠線の幅の設定(3)
        context.setLineWidth(CGFloat(self.strokeWidth))

        // 円を線で描く(4)
        // 円は引数のCGRectに内接するが50%がはみ出す
        context.strokeEllipse(in: rect)
    }

(1) コンテキストの取得

コンテキストを取得します。

(2) 描画色の設定

枠線の色の設定には"setStrokeColor"を使用します。
引数にはCGColorを指定します。
サンプルではStoryboardで設定した色を引数に渡しています。

(3) 枠線の幅の設定

枠線の幅を指定します。
サンプルではStoryboardで設定した数値を引数に渡しています。

(4) 枠線の円の描画

枠線の円は"strokeEllipse"で描画できます。
引数に指定したCGRectに内接する円が描かれますが、線の幅の半分が外側にはみ出します。塗りつぶしの円と同じCGRectの値を指定した場合、枠線の円の方が大きくなるので注意が必要です。

円を重ねて描画

CircleView.swift
override func draw(_ rect: CGRect) {
        // Viewに内接する円を塗りつぶしで描く(1)
        self.drawFillCircle(rect: rect)

        // 線の50%がViewの外に出るので内接するために調整したCGRectを用意する(2)
        let strokeRectSizeAdjustment = CGFloat(self.strokeWidth)
        let strokeRectSize = CGSize(width: rect.width - strokeRectSizeAdjustment, height: rect.height - strokeRectSizeAdjustment)
        let strokeRectPointAdjustment = strokeRectSizeAdjustment/2
        let strokeRectPoint = CGPoint(x: rect.origin.x + strokeRectPointAdjustment, y: rect.origin.y + strokeRectPointAdjustment)
        let strokeRect = CGRect(origin: strokeRectPoint, size: strokeRectSize)

        // Viewに内接する円を線で描く(3)
        self.drawStrokeCircle(rect: strokeRect)
    }

(1) 塗りつぶし円の描画

先に描画した図形が下になります。
枠線の円を上にしたいので、塗りつぶしの円を先に描画しています。

(2) 枠線の円が内接するCGRectを設定

上で説明しました通り、枠線の幅の半分がCGRectに内接した円の外側にはみ出すので、それを考慮して塗りつぶしの円と同じ大きさになるように枠線の円のCGRectを設定しています。

(3) 枠線の円の描画

(2)で設定したCGRectを渡して、塗りつぶしの円と同じ大きさになる枠線の円を描画しています。

サンプル

Githubにサンプルとして作成したプロジェクトを置いてあります。
CircleView

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8