从教程:http://swiftiostutorials.com/tutorial-draw-nice-triangle-view-border-cashapelayer/
,我设法创建了一个三角形,如:
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
}
}
但我想要实现的是一个三角形:
如何做到这一点?
答案 0 :(得分: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
}
}