gpt4 book ai didi

animation - 为在 drawRect() Swift 中绘制的贝塞尔曲线路径设置动画

转载 作者:IT王子 更新时间:2023-10-29 05:27:00 24 4
gpt4 key购买 nike

我在 drawRect()

中绘制了这个形状
var rectanglePath = UIBezierPath()

override func drawRect(rect: CGRect) {
rectanglePath = UIBezierPath(rect: self.bounds)
rectanglePath.fillWithBlendMode(kCGBlendModeMultiply, alpha: 0.7)
layer.shouldRasterize = true
}

prepareForEditing 函数被调用时,我想为 rectanglePath 设置动画。我试过了

  func prepareForEditing(editing:Bool){
UIView.animateWithDuration(0.5,
animations: {
self.rectanglePath = makeNewShape()
}
)
}

没有任何反应。你能告诉我我的代码有什么问题吗?

最佳答案

要为 CGPath 设置动画,您不能使用 UIView.animation 方法。我创建了自定义 UIView 子类来向您展示如何为 CGPaths 形状设置动画,请引用评论并根据您的要求进行修改:

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)
}
}

关于animation - 为在 drawRect() Swift 中绘制的贝塞尔曲线路径设置动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26847408/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com