2016-09-20 62 views
2

從教程支持:http://swiftiostutorials.com/tutorial-draw-nice-triangle-view-border-cashapelayer/,我成功地創造出像一個三角形:外形與UIView的三角形由CAShapeLayer

enter image description here

class Triangle: UIView { 
    override func drawRect(rect: CGRect) { 
     let mask = CAShapeLayer() 
     mask.frame = self.layer.bounds 

     let width = self.layer.frame.size.width 
     let height = self.layer.frame.size.height 

     let path = CGPathCreateMutable() 

     CGPathMoveToPoint(path, nil, 0, 0) 
     CGPathAddLineToPoint(path, nil, width, 0) 
     CGPathAddLineToPoint(path, nil, width, height) 
     CGPathAddLineToPoint(path, nil, width/2, height) 
     CGPathAddLineToPoint(path, nil, width, height) 


     mask.path = path 
     self.layer.mask = mask 
    } 
} 

但我想要實現的,是像一個三角形:

enter image description here

怎樣才能做到這一點?

回答

3

使用此路徑,而不是:

CGPathMoveToPoint(path, nil, 0, 0) 
CGPathAddLineToPoint(path, nil, width, 0) 
CGPathAddLineToPoint(path, nil, width/2, height) 
CGPathAddLineToPoint(path, nil, 0, 0) 

滿級:

class Triangle: UIView { 
    override func drawRect(rect: CGRect) { 
     let mask = CAShapeLayer() 
     mask.frame = self.layer.bounds 

     let width = self.layer.frame.size.width 
     let height = self.layer.frame.size.height 

     let path = CGPathCreateMutable() 

     CGPathMoveToPoint(path, nil, 0, 0) 
     CGPathAddLineToPoint(path, nil, width, 0) 
     CGPathAddLineToPoint(path, nil, width/2, height) 
     CGPathAddLineToPoint(path, nil, 0, 0) 

     mask.path = path 
     self.layer.mask = mask 
    } 
} 
+0

啊,沒注意額外的'CGPathAddLineToPoint'。謝了哥們 ! – Orange