運用 UIBezierPath 繪製海賊王名場面 — 火柴人版(解答在文章最後)
練習使用 SwiftUI 預覽 UIBezierPath 的繪圖
Published in
7 min readNov 23, 2022
前置作業:建立SwiftUI專案,將 ContentView.swift 原本的程式刪除,貼上以下程式
import SwiftUI
struct DrawView: UIViewRepresentable {
func makeUIView(context: Context) -> UIView {
let view = UIView()
>>這是之後要插入程式的地方
return view
}
func updateUIView(_ uiView: UIView, context: Context) {
}
}
struct ContentView: View {
var body: some View {
DrawView()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
先將找到的圖片放到畫面中,並將位置大小及透明度調成合適的值,方便對照描繪
let imageView = UIImageView(frame: CGRect(x: -25, y: 100, width: 460.5, height: 574.5))
imageView.image = UIImage(named: "Demo")
imageView.alpha = 0.3
view.addSubview(imageView)
原本的 view 當背景,宣告一個新的 view(containerView),用來放入畫好的 Layer
幫每個圖層建立 function,同時回到 func makeUIView,把圖層放進 containerView 中,這樣後續邊畫才會邊顯示目前畫完的樣子
struct DrawView: UIViewRepresentable {
func makeUIView(context: Context) -> UIView {
let view = UIView()
let containerView = UIView()
containerView.layer.addSublayer(blueHead())
containerView.layer.addSublayer(blueHand())
containerView.layer.addSublayer(blueHandDown())
containerView.layer.addSublayer(blueLegdown())
containerView.layer.addSublayer(blueLegUp())
containerView.layer.addSublayer(blueTriangle())
containerView.layer.addSublayer(redHead())
containerView.layer.addSublayer(redLeftHand())
containerView.layer.addSublayer(redHandDown())
containerView.layer.addSublayer(redRightHand())
containerView.layer.addSublayer(redRightLegUp())
containerView.layer.addSublayer(redRightLegDown())
containerView.layer.addSublayer(redLeftLegUp())
containerView.layer.addSublayer(redLeftLegDown())
view.addSubview(containerView)
return view
}
開始畫圖,在建立的 function 裡面畫圖,下面以藍色圓形為例,
func blueHead() -> CAShapeLayer {
let aDegree = CGFloat.pi / 180
let path = UIBezierPath()
path.addArc(withCenter: CGPoint(x: 107, y: 296), radius: 26.5, startAngle: aDegree * 0, endAngle: aDegree * (270+360), clockwise: true)
let layer = CAShapeLayer()
layer.path = path.cgPath
layer.fillColor = UIColor.blue.cgColor
return layer
}
最後加上動畫,懶得畫圖了直接下載圖片來練習
let imageView = UIImageView(frame: CGRect(x: 130, y: 500, width:50 , height: 60))
imageView.image = UIImage(named: "Thunder")
view.addSubview(imageView)
let imageView2 = UIImageView(frame: CGRect(x: 160, y: 280, width:50 , height: 60))
imageView2.image = UIImage(named: "Thunder")
view.addSubview(imageView2)
UIView.animate(withDuration: 1.5, delay: 0, options: [.repeat, .autoreverse], animations: {
imageView.layer.setAffineTransform(CGAffineTransform(scaleX: 1.2,y: 1.2).concatenating(CGAffineTransform(translationX: -10, y:-10)))
imageView2.layer.setAffineTransform(CGAffineTransform(scaleX: 1.2,y: 1.2).concatenating(CGAffineTransform(translationX: 10, y:0)))}, completion: {_ in })