ビューに図形を描きたい場合、
-
UIGraphicsImageRenderer
を利用し、UIImage
に図形をレンダリング -
UIImageView
を配置し、レンダリング画像を設定
のような方法を取るのが一般的かと思いますが、実は UIImageView
を配置しなくても、 UIView
だけでレンダリングした図形を表示する方法があります。
UIColor
のイニシャライザのひとつにinit(patternImage: UIImage)
というものがあり、これをUIView
のbackgroundColor
に設定すると、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も置いておきます。