我想像这样在 UITableView 单元格中显示三角形 View 。
我设法使用打击代码完成了此任务。
import UIKit
class TriangleView: UIView {
override func drawRect(rect: CGRect) {
let width = self.layer.frame.width
let height = self.layer.frame.height
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 0, 0)
CGPathAddLineToPoint(path, nil, width, 0)
CGPathAddLineToPoint(path, nil, 0, height)
CGPathAddLineToPoint(path, nil, 0, 0)
CGPathCloseSubpath(path)
let mask = CAShapeLayer()
mask.frame = self.layer.bounds
mask.path = path
self.layer.mask = mask
let shape = CAShapeLayer()
shape.frame = self.bounds
shape.path = path
shape.fillColor = UIColor.clearColor().CGColor
self.layer.insertSublayer(shape, atIndex: 0)
}
}
当我在搜索如何在 UIViews 中创建形状时,我发现您可以使用 UIBezierPath
来做同样的事情。所以我尝试使用 UIBezierPath
复制相同的东西。
let path = UIBezierPath()
path.moveToPoint(CGPoint(x: 0, y: 0))
path.moveToPoint(CGPoint(x: width, y: 0))
path.moveToPoint(CGPoint(x: 0, y: height))
path.moveToPoint(CGPoint(x: 0, y: 0))
path.closePath()
let mask = CAShapeLayer()
mask.frame = self.bounds
mask.path = path.CGPath
self.layer.mask = mask
let shape = CAShapeLayer()
shape.frame = self.bounds
shape.path = path.CGPath
shape.fillColor = UIColor.clearColor().CGColor
self.layer.insertSublayer(shape, atIndex: 0)
但这根本行不通。没有显示任何形状。
我需要做任何额外的事情才能让它正常工作吗?
最佳答案
你让这件事变得比它需要的更难。您只需要添加一个带有路径的形状图层,并设置该图层的fillColor
。但是,您的代码不起作用的主要原因是因为您对所有行都使用 moveToPoint
而不是对第一行以外的所有行使用 addLineToPoint
。
class TriangleView: UIView {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
let path = UIBezierPath()
path.moveToPoint(CGPoint(x: 0, y: 0))
path.addLineToPoint(CGPoint(x: frame.size.width, y: 0))
path.addLineToPoint(CGPoint(x: 0, y: frame.size.height))
path.closePath()
let shape = CAShapeLayer()
shape.frame = self.bounds
shape.path = path.CGPath
shape.fillColor = UIColor.blueColor().CGColor
self.layer.addSublayer(shape)
}
}
关于ios - 带有 UIBezierPath 的 CAShapeLayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29476587/