Changing cornerRadius using Core Animation

只愿长相守 提交于 2019-12-09 11:10:39

问题


I am trying to change the corner radius of a button (OpenNoteVisible.layer) in the following way:

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"cornerRadius"];
animation.timingFunction = [CAMediaTimingFunction     functionWithName:kCAMediaTimingFunctionLinear];
animation.fromValue = [NSNumber numberWithFloat:10.0f];
animation.toValue = [NSNumber numberWithFloat:0.0f];
animation.duration = 1.0;
[animation.layer setCornerRadius:140.0];
[OpenNoteVisible.layer addAnimation:animation forKey:@"cornerRadius"];

But this code gives an error at the line [animation.layer setCornerRadius:140.0]; I can't understand why. I have imported Quartz core framework.


回答1:


You're setting the corner radius on the layer property of the animation object; this animation object doesn't have a layer property.

You need to set the corner radius on the layer of the thing you're animating, in this case OpenNoteVisible. You also need to ensure the toValue of the animation object matches the value you're setting on the layer, otherwise you'll get odd animations.

Your code should now be:

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"cornerRadius"];
animation.timingFunction = [CAMediaTimingFunction     functionWithName:kCAMediaTimingFunctionLinear];
animation.fromValue = [NSNumber numberWithFloat:10.0f];
animation.toValue = [NSNumber numberWithFloat:140.0f];
animation.duration = 1.0;
[OpenNoteVisible.layer setCornerRadius:140.0];
[OpenNoteVisible.layer addAnimation:animation forKey:@"cornerRadius"];



回答2:


Swift 4 solution is below

import UIKit
import PlaygroundSupport

let view = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
view.backgroundColor = #colorLiteral(red: 1, green: 0.5763723254, blue: 0, alpha: 1)
PlaygroundPage.current.liveView = view

UIView.animate(withDuration: 2.5, animations: {
    view.layer.cornerRadius = 40
}, completion: { _ in
    UIView.animate(withDuration: 0.5, animations: {
        view.layer.cornerRadius = 0
    })
})


来源:https://stackoverflow.com/questions/18511359/changing-cornerradius-using-core-animation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!