LoginSignup
3
3

More than 3 years have passed since last update.

Swift:NSGraphicsContextを使って描画する

Last updated at Posted at 2018-07-11

背景

普段、簡単な図形の描画はNSBezierPathを使って行うのだが、描画色の細かい設定を変更したくなった際に、CGContextsetBlendMode()を使うためにNSGraphicsContextを利用した図形描画を行う必要に迫られた。その際の方法をまとめる。

現状この記事にまとめられている方法はNSGraphicsContextではなくCGContextを使った図形描画手法になってしまっている... 後で修正する

ソースコード(2018/7/11 Swift4対応版)

import Cocoa

class SampleView: NSView {

    required init?(coder decoder: NSCoder) {
        super.init(coder: decoder)

        wantsLayer = true
        layer?.backgroundColor = NSColor.gray.cgColor
    }

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        if let context = NSGraphicsContext.current?.cgContext {
            context.beginPath()

            // 線の幅の設定
            context.setLineWidth(2.0)
            // 線の色の設定
            context.setStrokeColor(CGColor.black)
            // 塗りつぶし色の設定
            context.setFillColor(CGColor.white)
            // 描画色のモード設定
            context.setBlendMode(CGBlendMode.multiply)

            // 既存のCGPathを使う場合
            context.addPath(path.cgPath)
            // パスの移動
            context.move(to: CGPoint)
            // 直線パスの追加
            context.addLine(to: CGPoint)
            // 曲線パスの追加
            context.addCurve(to: CGPoint, control1: CGPoint, control2: CGPoint)
            // 四角形パスの追加
            context.addRect(CGRect)

            // 中塗りパスの描画
            context.fillPath()
            // パスのアウトラインの描画
            context.strokePath()
        }
    }
}

備考

上に挙げた他にも大量の図形描画にまつわるメソッドが存在する。

3
3
0

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
3
3