【发布时间】:2016-05-14 21:02:37
【问题描述】:
为了节省任何在这里搜索的人的时间,我错误地认为clearsContextBeforeDrawing 会同时清除在 drawRect 中添加的任何图层。它没有。
当然,正如马特所解释的,你当然应该只在 drawRect 中绘制普通的方式,然后clearsContextBeforeDrawing 才能正常工作。例如,
override func drawRect(rect: CGRect)
{
// clearsContextBeforeDrawing works perfectly here as normal
// don't add any layers in here :)
let dotPath = UIBezierPath(ovalInRect:rect)
mainColor.setFill()
dotPath.fill()
let ins:CGFloat = ( ringThickness / 2 )
let circlePath = UIBezierPath(ovalInRect: CGRectInset(rect,ins,ins) )
circlePath.lineWidth = ringThickness
ringColor.setStroke()
circlePath.stroke()
}
这是drawRect的一种糟糕的绘制方式
override func drawRect(rect: CGRect)
{
let circlePath = UIBezierPath(ovalInRect:rect)
let circle = CAShapeLayer()
circle.path = circlePath.CGPath
circle.fillColor = someColor.CGColor
layer.addSublayer(circle)
... and a few more layers like ...
blah.fillColor = someColor.CGColor
layer.addSublayer(blah)
}
但是如何在绘制前清除呢?
设置clearsContextBeforeDrawing 没有任何作用。
我可以清除的唯一方法是删除所有图层:
override func drawRect(rect: CGRect)
{
// first remove all layers...
if let sublayers = layer.sublayers {
for layer in sublayers {
if layer.isKindOfClass(CAShapeLayer) //(essential)
{ layer.removeFromSuperlayer() }
}
}
...
}
有没有更好的清除“图层”绘图的方法?
【问题讨论】:
标签: ios swift calayer drawrect