对在drawRect()中绘制的贝塞尔曲线路径进行动画处理 [英] Animate a bezier path drawn in drawRect() Swift
本文介绍了对在drawRect()中绘制的贝塞尔曲线路径进行动画处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的形状,我会画在 drawRect()
I have this shape that i draw in drawRect()
var rectanglePath = UIBezierPath()
override func drawRect(rect: CGRect) {
rectanglePath = UIBezierPath(rect: self.bounds)
rectanglePath.fillWithBlendMode(kCGBlendModeMultiply, alpha: 0.7)
layer.shouldRasterize = true
}
当 prepareForEditing
函数被调用,我想给矩形路径设置动画。我尝试过
When prepareForEditing
function is called, i want to animate the rectanglePath. I tried
func prepareForEditing(editing:Bool){
UIView.animateWithDuration(0.5,
animations: {
self.rectanglePath = makeNewShape()
}
)
}
什么都没有发生。您能告诉我我的代码有什么问题吗?
Nothing happens. Can you please tell me what's wrong with my code?
推荐答案
要为CGPath设置动画,您不能使用UIView.animation方法。
我创建了自定义UIView子类,以向您展示如何为CGPaths形状制作动画,请参考注释并根据您的要求进行修改:
To animate CGPath you cannot use UIView.animation methods. I created custom UIView subclass to show you how can you animate CGPaths shape, please refer to the comments and amend it for your requirements:
class MyView: UIView {
let shapeLayer = CAShapeLayer()
let maskLayer = CAShapeLayer()
var rectanglePath = UIBezierPath()
override func didMoveToSuperview() {
super.didMoveToSuperview()
backgroundColor = UIColor.clear
// initial shape of the view
rectanglePath = UIBezierPath(rect: bounds)
// Create initial shape of the view
shapeLayer.path = rectanglePath.cgPath
shapeLayer.strokeColor = UIColor.black.cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
layer.addSublayer(shapeLayer)
//mask layer
maskLayer.path = shapeLayer.path
maskLayer.position = shapeLayer.position
layer.mask = maskLayer
}
func prepareForEditing(editing:Bool){
let animation = CABasicAnimation(keyPath: "path")
animation.duration = 2
// Your new shape here
animation.toValue = UIBezierPath(ovalIn: bounds).cgPath
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
// The next two line preserves the final shape of animation,
// if you remove it the shape will return to the original shape after the animation finished
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
shapeLayer.add(animation, forKey: nil)
maskLayer.add(animation, forKey: nil)
}
}
这篇关于对在drawRect()中绘制的贝塞尔曲线路径进行动画处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文