LoginSignup
2
6

More than 5 years have passed since last update.

UIViewを簡単にキャンバス化する

Posted at

ビューに図形を描きたい場合、

  • UIGraphicsImageRenderer を利用し、 UIImage に図形をレンダリング
  • UIImageView を配置し、レンダリング画像を設定

のような方法を取るのが一般的かと思いますが、実は UIImageView を配置しなくても、 UIView だけでレンダリングした図形を表示する方法があります。

UIColor のイニシャライザのひとつに init(patternImage: UIImage) というものがあり、これを UIViewbackgroundColor に設定すると、 UIView に画像を表示することができるのです。

UIView+Render.swift
extension UIView {
    func render(actions: (UIGraphicsImageRendererContext) -> Void) {
        let renderer = UIGraphicsImageRenderer(size: self.bounds.size)
        let image = renderer.image(actions: actions)
        self.backgroundColor = UIColor(patternImage: image)
    }
}

上記のような extension を追加すれば、図形を簡単にレンダリングできるようになります。

// 楕円をランダムに描画
view.render { (context) in
    context.cgContext.clear(view.bounds)

    for _ in 0...50 {
        let rect = CGRect(
            x: .random(in: 0...300),
            y: .random(in: 0...600),
            width: .random(in: 50...100),
            height: .random(in: 50...100)
        )

        let color = UIColor(
            red: .random(in: 0...1),
            green: .random(in: 0...1),
            blue: .random(in: 0...1),
            alpha: 1.0
        )
        color.setFill()
        context.cgContext.fillEllipse(in: rect)
    }
}

Playgroundも置いておきます。

2
6
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
2
6