TL; DR: 基本上我的问题与这个问题相同:CAGradientLayer, not resizing nicely, tearing on rotation. (video of issue attached)
我按照Rob Mayoff的优秀答案(一如既往)。我的问题是我没有使用CAGradientLayer而是 CAShapeLayer 而且它不起作用
我使用CAShapeLayer而不是UIBezierPath,因为我需要为路径颜色和阴影设置动画。
虽然,问题在于设备旋转时路径的形状:CAShapeLayer的动画看起来很糟糕,实际上它甚至没有动画,它只是立即安排到新边界的路径。
我曾经将CAShapeLayer添加为子图层,但是在这里阅读一些答案我尝试将UIView子类化并将其图层设置为CAShapeLayer,以便视图自动管理旋转动画,但结果是相同的。
如果我使用UIBezierPath进行绘制,它确实可以正常工作(但不幸的是我需要CAShapeLayer功能)
这是我的代码:
import UIKit
class CaShapeLayerView: UIView {
override class func layerClass () -> AnyClass{
return CAShapeLayer.self
}
override func drawRect(rect: CGRect) {
var bezierPath = UIBezierPath()
// create a random scribble :)
bezierPath.moveToPoint(CGPoint(x: 0, y: 0))
bezierPath.addCurveToPoint(CGPoint(x:self.bounds.width, y:self.bounds.height), controlPoint1: CGPoint(x: self.bounds.width/50, y: self.bounds.height/2), controlPoint2: CGPoint(x: self.bounds.width/40, y: self.bounds.height/8*10))
// draw UIBezierPath
UIColor.redColor().set()
bezierPath.lineWidth = 20
bezierPath.stroke()
// draw CAShapeLayer
var shapeLayer = self.layer as CAShapeLayer
shapeLayer.strokeColor = UIColor.blueColor().CGColor
shapeLayer.fillColor = nil
shapeLayer.lineWidth = 16
shapeLayer.path = bezierPath.CGPath
}
}
旋转设备,您将获得红色的UIBezierPath和蓝色的CAShapeLayer之间的差异。 我用我的实际路径向CAShapeLayer保证“动画”很糟糕。
我错过了什么吗?
非常感谢大家。
答案 0 :(得分:1)
drawRect
上的此代码无法设置动画:
UIColor.redColor().set()
bezierPath.lineWidth = 20
bezierPath.stroke()
这就是您的图片partially
重绘设备轮播
你需要这样的东西:
class CAShapeLayerView: UIView {
var firstShapeLayer, secondShapeLayer:CAShapeLayer
required init(coder aDecoder: NSCoder) {
firstShapeLayer = CAShapeLayer()
secondShapeLayer = CAShapeLayer()
super.init(coder: aDecoder)
}
override class func layerClass () -> AnyClass{
return CAShapeLayer.self
}
override func awakeFromNib() {
self.firstShapeLayer.lineWidth = 20
self.firstShapeLayer.strokeColor = UIColor.redColor().CGColor
self.firstShapeLayer.fillColor = nil
self.secondShapeLayer.strokeColor = UIColor.blueColor().CGColor
self.secondShapeLayer.fillColor = nil
self.secondShapeLayer.lineWidth = 16
self.layer.addSublayer(self.firstShapeLayer)
self.layer.addSublayer(self.secondShapeLayer)
}
override func layoutSubviews() {
super.layoutSubviews();
var bezierPath = UIBezierPath()
// create a random scribble :)
bezierPath.moveToPoint(CGPoint(x: 0, y: 0))
bezierPath.addCurveToPoint(CGPoint(x:self.bounds.width, y:self.bounds.height), controlPoint1: CGPoint(x: self.bounds.width/50, y: self.bounds.height/2), controlPoint2: CGPoint(x: self.bounds.width/40, y: self.bounds.height/8*10))
self.firstShapeLayer.path = bezierPath.CGPath
self.secondShapeLayer.path = bezierPath.CGPath
}
}