iOS 使用貝塞爾曲線繪製路徑
教學連結
範例
繪製一段圓弧 如果是合起來的就是圓了
let criclePath: UIBezierPath = UIBezierPath.init(arcCenter: CGPoint.init(x: 200, y: 100), radius: 50, startAngle: 0, endAngle: 5.12, clockwise: true) criclePath.stroke()
繪製一個矩形
let rectPath: UIBezierPath = UIBezierPath.init(rect: CGRect.init(x: 100, y: 160, width: 50, height: 50)) criclePath.append(rectPath)
繪製一個橢圓 原理是內接矩形,如果矩形的長寬相等那幺繪製的就是圓
let ovalPath:UIBezierPath = UIBezierPath.init(ovalIn: CGRect.init(x: 200, y: 200, width: 100, height: 60)) criclePath.append(ovalPath)
繪製直線多邊形 可以讓多條直線拼接 組合成複雜的形狀 比如繪製一個三角形
let trianglePath :UIBezierPath = UIBezierPath.init() trianglePath.move(to: CGPoint.init(x: 100, y: 300)) //繪製起始點 trianglePath.addLine(to: CGPoint.init(x: 100, y: 400)) //從起點繪製一條直線到指定點 trianglePath.addLine(to: CGPoint.init(x: 250, y: 350)) // trianglePath.close() //閉合路徑 trianglePath.lineWidth = 3.0 criclePath.append(trianglePath)
添加一個二階的曲線 二階曲線一共是三個點, 起點/終點/折點(控制點)
let cruvePath :UIBezierPath = UIBezierPath.init() cruvePath.move(to: CGPoint.init(x: 50, y: 420)) cruvePath.addQuadCurve(to: CGPoint.init(x: 250, y: 420), controlPoint: CGPoint.init(x: 100, y: 530)) criclePath.append(cruvePath)
添加一個三階的曲線 起點 終點 兩個控制點 後面可以無限添加 二階曲線 形成一個很長的三階曲線
let path :UIBezierPath = UIBezierPath.init() path.move(to: CGPoint.init(x: 50, y: 550)) path.addCurve(to: CGPoint.init(x: 287, y: 550), controlPoint1: CGPoint.init(x: 150, y: 720), controlPoint2: CGPoint.init(x: 215, y: 410)) path.addQuadCurve(to: CGPoint.init(x: 350, y: 550), controlPoint: CGPoint.init(x: 324, y: 610)) criclePath.append(path)
創建一個CAShapelayer 用於顯示這些路徑
let shPl: CAShapeLayer = CAShapeLayer.init() shPl.path = criclePath.cgPath shPl.lineWidth = 3.0 shPl.fillColor = UIColor.clear.cgColor //填充路徑 shPl.strokeColor = UIColor.red.cgColor //描繪路徑 根據線寬來描繪 self.view.layer.addSublayer(shPl) self.view.layer.backgroundColor = UIColor.white.cgColor
完成圖
Last updated
Was this helpful?