LoginSignup
0
1

More than 1 year has passed since last update.

Playground環境でUIBezierPathを触ってみる

Posted at

概要

XcodeのPlayground環境を使えば、UIBezierPathを使った開発が捗りました。
共有します。

環境

macOS Big Sur 11.6
Xcode 13.1

手順

ざっくり次のような感じです。
1. PlaygroundSupportをインポートする
2. 図形を描画するためのViewを実装する
3. Viewをプレビューできるように設定する

1. PlaygroundSupportをインポートする

PlaygroundSupportをインポートしてください。

MyPlayground
import PlaygroundSupport

2. 図形を描画するためのViewを実装する

UIViewを継承したCustomViewを作成します。
draw(_:)メソッドで図形を描画する処理を記述します。

MyPlayground
override func draw(_ rect: CGRect) {
    let rect = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 200, height: 100), byRoundingCorners: .bottomRight, cornerRadii: CGSize(width: 10, height: 10))
    UIColor.link.setStroke()
    rect.lineWidth = 4    
    rect.stroke()
}

3. Viewをプレビューできるように設定する

PlaygroundPageliveViewというプロパティにカスタムViewのインスタンスを設定します。

MyPlayground
let customView = CustomView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
customView.backgroundColor = .white
PlaygroundPage.current.liveView = customView

全体のコードはこちらです。

MyPlayground
import UIKit
import PlaygroundSupport

class CustomView: UIView {
    override func draw(_ rect: CGRect) {
        radiusRect()
    }

    private func radiusRect() {
        let rect = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 200, height: 100), byRoundingCorners: .bottomRight, cornerRadii: CGSize(width: 10, height: 10))
        UIColor.link.setStroke()
        rect.lineWidth = 4
        rect.stroke()
    }
}

let customView = CustomView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
customView.backgroundColor = .white
PlaygroundPage.current.liveView = customView

画像のようにプレビューできると思います。

0
1
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
0
1