ios開發之在UIView上使用自訂曲線繪製複雜圖形(貝茲路徑)

來源:互聯網
上載者:User

有時我們需要繪製一個不規則路徑的圖形,裡面可能包含直線或者曲線,這時就可以使用 UIBezierPath 來實現。

 
UIBezierPath類可以表示任何能夠用Bezier曲線定義的形狀,我們可以建立自己的自訂曲線。完成操作後,可以像其他路徑一樣,使用所得到的UIBezierPath對象進行填充和描邊。
 
1,下面示範使用UIBezierPath繪製一個不規則圖形:
(1)畫筆移動到矩形地區左上方
(2)從筆的當前位置向右上方的點畫一條直線
(3)從筆的當前位置向左下角的點畫一條直線
(4)從筆的當前位置向右下角畫一條曲線,曲線彎曲程度的兩個控制點是矩形地區的中點
(5)從筆的當前位置向左上方的點繪製一條直線,使路徑閉合
 
2,效果圖如下:
 
3,代碼如下:

 

 代碼如下 複製代碼
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 bezierPath = UIBezierPath()
         
        //建立一個矩形,它的所有邊都內縮5%
        let drawingRect = CGRectInset(self.bounds,
            self.bounds.size.width * 0.05,
            self.bounds.size.height * 0.05)
   
        //確定組成繪畫的點
        let topLeft = CGPointMake(CGRectGetMinX(drawingRect),
            CGRectGetMinY(drawingRect))
         
        let topRight = CGPointMake(CGRectGetMaxX(drawingRect),
            CGRectGetMinY(drawingRect))
         
        let bottomRight = CGPointMake(CGRectGetMaxX(drawingRect),
            CGRectGetMaxY(drawingRect))
         
        let bottomLeft = CGPointMake(CGRectGetMinX(drawingRect),
            CGRectGetMaxY(drawingRect))
         
        let center = CGPointMake(CGRectGetMidX(drawingRect),
            CGRectGetMidY(drawingRect))
         
        //開始繪製
        bezierPath.moveToPoint(topLeft)
        bezierPath.addLineToPoint(topRight)
        bezierPath.addLineToPoint(bottomLeft)
        bezierPath.addCurveToPoint(bottomRight, controlPoint1: center, controlPoint2: center)
         
        //使路徑閉合,結束繪製
        bezierPath.closePath()
         
        //設定顏色,並繪製它們
        UIColor.greenColor().setFill()
        UIColor.blackColor().setStroke()
         
        bezierPath.fill()
        bezierPath.stroke()
    }
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.