需要繼承UIView 重寫draw 方法

image.png
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let mview = myView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
self.view.addSubview(mview)
let mview2 = myView(frame: CGRect(x: 0, y:200, width: 300, height: 300))
self.view.addSubview(mview2)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//自定義View
class myView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
//清除背景顏色
self.backgroundColor = UIColor.clear
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func draw(_ rect: CGRect) {
super.draw(rect)
//獲取繪圖上下文
guard let context = UIGraphicsGetCurrentContext() else { return }
//創(chuàng)建并設(shè)置路徑
let path = CGMutablePath()
path.move(to: CGPoint(x: 10, y: 10))
path.addLine(to: CGPoint(x: 200, y: 222))
let secondP = CGMutablePath()
secondP.move(to: CGPoint(x: 300, y: 0 ))
secondP.addLine(to: CGPoint(x: 200, y: 222))
//設(shè)置描線顏色
context.setStrokeColor(UIColor.black.cgColor)
//將路徑添加到上下文
context.addPath(path)
context.addPath(secondP)
//設(shè)置線寬
context.setLineWidth(10)
//開始繪制路徑
context.strokePath()
}
}