#22.運用 UIBezierPath 繪製可愛圖案
Published in
4 min readMay 5, 2022
#5–5.HomeWorks; 使用BezierPath畫一個 3D 浣熊吧
在Project建立一個SwiftUI的檔案
在專案中將 ContentView.swift 原本的程式刪除,貼上以下程式。以下程式將利用 SwiftUI 幫我們預覽繪製的圖案
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()
}
}
建立背景顏色&定義部位的View
let view = UIView()view.backgroundColor = UIColor.init(cgColor: CGColor.init(srgbRed: 1, green: 229/255, blue: 290/255, alpha: 1))let containerView = UIView()let handView = UIView()
let bodyView = UIView()
let tailView = UIView()
let tail2View = UIView()
定義每個BezierPath加入圖層
containerView.layer.addSublayer(addLeftEars())
containerView.layer.addSublayer(addLeftBackEars())
containerView.layer.addSublayer(addRightEars())
containerView.layer.addSublayer(addhead1())
containerView.layer.addSublayer(addhead2())
containerView.layer.addSublayer(addhead3())
......
將每一圖層加入到View中,畫面才會顯現出來
view.addSubview(containerView)
view.addSubview(bodyView)
view.addSubview(handView)
view.addSubview(tailView)
view.addSubview(tail2View)
使用曲線劃每一個區塊
func addLeftEars() -> CAShapeLayer{ let path = UIBezierPath()//開指定義每一塊的點,並用線條化成區塊
path.move(to: CGPoint(x: 39, y: 54)) //左下點
path.addLine(to: CGPoint(x: 39, y: 22)) //左上點
path.addLine(to: CGPoint(x: 46, y: 11)) //右上點
path.addLine(to: CGPoint(x: 62, y: 30)) //右下點
path.close() //收尾 let planetLayer = CAShapeLayer()
planetLayer.path = path.cgPath
planetLayer.fillColor = CGColor(srgbRed: 47/255, green: 51/255, blue: 66/255, alpha: 1)
planetLayer.strokeColor = UIColor.black.cgColor
planetLayer.lineWidth = 0.3return planetLayer}