我正在尝试动画CALayer的边界并且它不起作用。这是代码:
class CircleView < UIIVew
def initWithFrame(frame)
super
# determine the dimensions
radius = (bounds.size.width < bounds.size.height ? bounds.size.width : bounds.size.height) / 2
# create the circle layer
@circle = CAShapeLayer.layer
@circle.bounds = bounds
@circle.path = UIBezierPath.bezierPathWithRoundedRect(bounds, cornerRadius: radius).CGPath
@circle.fillColor = UIColor.blueColor.CGColor
# add the circle to the view
self.layer.addSublayer(@circle)
shrink
self
end
private
# Applies the shrink animation to the provided circle layer.
def shrink
# determine the bounds
old_bounds = @circle.bounds
new_bounds = CGRectMake(old_bounds.size.width / 2, old_bounds.size.height / 2, 0, 0)
# animate the shrinking
animation = CABasicAnimation.animationWithKeyPath("bounds")
animation.fromValue = NSValue.valueWithCGRect(old_bounds)
animation.toValue = NSValue.valueWithCGRect(new_bounds)
animation.duration = 3.0
@circle.addAnimation(animation, forKey:"bounds")
# set the bounds so the animation doesn't bounce back when it's complete
@circle.bounds = new_bounds
end
# Applies the shrink animation to the provided circle layer.
def disappear
# animate the shirnk
animation = CABasicAnimation.animationWithKeyPath("opacity")
animation.fromValue = NSNumber.numberWithFloat(1.0)
animation.toValue = NSNumber.numberWithFloat(0.0)
animation.duration = 3.0
@circle.addAnimation(animation, forKey:"opacity")
# set the value so the animation doesn't bound back when it's completed
@circle.opacity = 0.0
end
end
如果我从initWithFrame
方法调用消失,动画效果正常。但是,调用shrink无效。我做错了什么?
答案 0 :(得分:6)
那是因为您使用的是CAShapeLayer
。 path
独立于bounds
,因此您必须单独为其设置动画。
我可以使用大致翻译为Objective C的代码版本重现您的问题。当我将shrink
方法更改为此时,它可以工作:
-(void)shrink
{
CGRect old_bounds = self.circle.bounds;
CGRect new_bounds = CGRectMake(old_bounds.size.width / 2, old_bounds.size.height / 2, 0, 0);
// bounds
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath: @"bounds"];
animation.fromValue = [NSValue valueWithCGRect: old_bounds];
animation.toValue = [NSValue valueWithCGRect: new_bounds];
animation.duration = 3.0;
[self.circle addAnimation: animation forKey: @"bounds"];
// path
CGPathRef old_path = self.circle.path;
CGPathRef new_path = [UIBezierPath bezierPathWithRoundedRect:new_bounds cornerRadius:0].CGPath;
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath: @"path"];
pathAnimation.fromValue = (__bridge id)(old_path);
pathAnimation.toValue = (__bridge id)(new_path);
pathAnimation.duration = 3.0;
[self.circle addAnimation: pathAnimation forKey: @"path"];
//set the value so the animation doesn't bound back when it's completed
self.circle.bounds = new_bounds;
self.circle.path = new_path;
}
从技术上讲,您甚至可能不需要为边界设置动画。如果您在backgroundColor
图层上设置了不同的circle
,则可以稍微进行一些实验,更轻松地了解bounds
和path
如何设置和动画或多或少独立(例如,在您的原始代码中,您可以看到边界实际上是动画的,但路径保持不变。)
答案 1 :(得分:-2)
不知道Ruby,我建议调整框架而不是边界。边界位于CALayers自己的坐标系中,与图层本身在父级中的显示方式无关。