美文网首页
iOS swift 画线

iOS swift 画线

作者: 稀释1 | 来源:发表于2021-11-09 17:01 被阅读0次

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

    }

}

相关文章

网友评论

      本文标题:iOS swift 画线

      本文链接:https://www.haomeiwen.com/subject/cpxvzltx.html