Swift開發在UIView上繪製矩形(直角,圓角,帶邊框)

來源:互聯網
上載者:User

當系統要顯示一個視圖(UIView)時,它會向視圖發送drawRect(rect:)訊息。所以,如果我們需要在視圖上進行繪製,則可以在drawRect方法內部實現。

 

1,用純色填充的矩形

下面建立一個長寬都為100的矩形UIView,座標(50,50)。其內部使用綠色填充。

 

 代碼如下 複製代碼
import UIKit
 
class ViewController: UIViewController {
 
    override func viewDidLoad() {
        super.viewDidLoad()
         
        let viewRect = CGRect(x: 50, y: 50, width: 100, height: 100)
        let view1 = MyCanvas(frame: viewRect)
        self.view.addSubview(view1)
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
 
class MyCanvas: UIView {
    override func drawRect(rect: CGRect) {
        UIColor.greenColor().setFill()
        let path = UIBezierPath(rect: self.bounds)
        path.fill()
    }
}

2,繪製圓角矩形,同時添加外部邊框輪廓

(1)在對一個路徑描邊時,輪廓線是在路徑上繪製的。由於設定輪廓線寬度為3,為了讓輪廓線不會被邊緣裁去一部分,使用 CGRectInset函數保持中心點不變的情況下矩形內縮一個點。

(2)重寫init(frame: CGRect) 方法,將背景色設為透明,否則背景是黑色的(四個圓角透明部分會顯示黑色)

 

 代碼如下 複製代碼

import UIKit
 
class ViewController: UIViewController {
 
    override func viewDidLoad() {
        super.viewDidLoad()
         
        let viewRect = CGRect(x: 50, y: 50, width: 100, height: 100)
        let view1 = MyCanvas(frame: viewRect)
        self.view.addSubview(view1)
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
 
class MyCanvas: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        //把背景色設為透明
        self.backgroundColor = UIColor.clearColor()
    }
 
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
     
    override func drawRect(rect: CGRect) {
        let pathRect = CGRectInset(self.bounds, 1, 1)
        let path = UIBezierPath(roundedRect: pathRect, cornerRadius: 10)
        path.lineWidth = 3
        UIColor.greenColor().setFill()
        UIColor.blueColor().setStroke()
        path.fill()
        path.stroke()
    }
}

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.