iOS swift 画线

需要继承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  }

        

        

        //创建并设置路径

        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()

    }

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容