iOS*_*Dev 31 objective-c calayer ios
我正在以这种方式将边框宽度和颜色设置为UIView子类:
- (void) setViewBorder
{
self.layer.borderColor = [UIColor greenColor].CGColor;
self.layer.borderWidth = 3.0f;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:我怎样才能为此设置动画?谢谢.
Dav*_*ist 56
这两个borderColor和borderWidth是动画的属性,但因为你是一个的UIView动画块外这样在视图中的子类,隐式动画(那些当您更改一个值,自动发生)被禁用.
如果要为这些属性设置动画,则可以使用a进行显式动画CABasicAnimation.由于您在同一图层上设置了两个属性的动画,因此可以将它们添加到动画组中,并仅配置一次持续时间,时间等.请注意,显式动画纯粹是可视化的,添加它们时模型值(实际属性)不会更改.这就是您配置动画和设置模型值的原因.
CABasicAnimation *color = [CABasicAnimation animationWithKeyPath:@"borderColor"];
// animate from red to blue border ...
color.fromValue = (id)[UIColor redColor].CGColor;
color.toValue = (id)[UIColor blueColor].CGColor;
// ... and change the model value
self.layer.borderColor = [UIColor blueColor].CGColor;
CABasicAnimation *width = [CABasicAnimation animationWithKeyPath:@"borderWidth"];
// animate from 2pt to 4pt wide border ...
width.fromValue = @2;
width.toValue = @4;
// ... and change the model value
self.layer.borderWidth = 4;
CAAnimationGroup *both = [CAAnimationGroup animation];
// animate both as a group with the duration of 0.5 seconds
both.duration = 0.5;
both.animations = @[color, width];
// optionally add other configuration (that applies to both animations)
both.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[self.layer addAnimation:both forKey:@"color and width"];
Run Code Online (Sandbox Code Playgroud)
如果您在"设置插值"部分下查看CABasicAnimation的文档,您将看到没有必要像我一样指定toValue和fromValue,因此可以稍微缩短代码.但是,为了清晰和可读性(特别是当您开始使用Core Animation时)更明确可以帮助您(和您的同事)理解代码.
Mes*_*ery 24
这是@David答案的快速解决方案:
let colorAnimation = CABasicAnimation(keyPath: "borderColor")
colorAnimation.fromValue = UIColor.red.cgColor
colorAnimation.toValue = UIColor.blue.cgColor
view.layer.borderColor = UIColor.blue.cgColor
let widthAnimation = CABasicAnimation(keyPath: "borderWidth")
widthAnimation.fromValue = 2
widthAnimation.toValue = 4
widthAnimation.duration = 4
view.layer.borderWidth = 4
let bothAnimations = CAAnimationGroup()
bothAnimations.duration = 0.5
bothAnimations.animations = [colorAnimation, widthAnimation]
bothAnimations.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
view.layer.add(bothAnimations, forKey: "color and width")
Run Code Online (Sandbox Code Playgroud)
如果你只想淡入边框,你也可以这样做:
UIView.transition(with: self, duration: 0.3, options: .transitionCrossDissolve, animations: {
self.layer.borderColor = UIColor.green.cgColor
self.layer.borderWidth = 3
}, completion: nil)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17807 次 |
| 最近记录: |