Swift . Core Graphics 画线
需要继承UIView 重写draw 方法
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 }
//创建并设置路径
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))
//设置描线颜色
context.setStrokeColor(UIColor.black.cgColor)
//将路径添加到上下文
context.addPath(path)
context.addPath(secondP)
//设置线宽
context.setLineWidth(10)
//开始绘制路径
context.strokePath()
}
}