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  }

        

        

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

    }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容