音乐播放旋转动画

@interface RootViewController ()

@property (nonatomic, retain) UIImageView *image;


@property(nonatomic,assign)BOOL isSelected;

@end


@implementation RootViewController


- (void)createButtView

{

    

    

    self.image = [[UIImageView alloc] initWithFrame:CGRectMake(100, 300, 100, 100)];

    _image.backgroundColor = [UIColor cyanColor];

    _image.layer.cornerRadius = 50;

    self.image.image = [UIImage imageNamed:@"iconfont-bofang"];

   

    [self.view addSubview:_image];

    

     CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];

    animation.duration = 1;

    animation.fromValue = [NSNumber numberWithInt:0];

    animation.toValue = [NSNumber numberWithInt:2 * M_PI];

    // 动画重复次数

    [animation setRepeatCount:NSIntegerMax];

    // 播放完毕后是否逆向回到原位置

    [animation setAutoreverses:NO];

    // 是否要有叠加的效果

    [animation setCumulative:YES];

  

    // 停止动画的速度设为0

    self.image.layer.speed = 0;

    [self.image.layer addAnimation:animation forKey:@"animtation"];

    

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];

    [self.image addGestureRecognizer:tap];

    

     self.image.userInteractionEnabled = YES;


}

-(void)tapAction:(UITapGestureRecognizer *)tap

{

    //系统给UIView设置了属于view自己的时间系统

    //通过改变view的时间来改变他得动画开始和结束

    //获得点击图片时的动画时间,为了下次开始动画用

    if (self.isSelected == YES) {

        CFTimeInterval stopTime = [self.image.layer convertTime:CACurrentMediaTime() fromLayer:nil];

        //停止动画,速度设置为0

        self.image.layer.speed = 0;

        //设置时间偏移量

        self.image.layer.timeOffset = stopTime;

    }else{

        //开始旋转

        //得到view当前动画时间偏移量

        CFTimeInterval stopTime = [self.image.layer timeOffset];

        //初始化开始时间

        self.image.layer.beginTime = 0;

        //初始化时间偏移量

        self.image.layer.timeOffset = 0;

        //设置动画速度

        self.image.layer.speed = 1;

        //计算时间差

        CFTimeInterval tempTime = [self.image.layer convertTime:CACurrentMediaTime() fromLayer:nil] - stopTime;

        //重新设置动画开始时间

        self.image.layer.beginTime = tempTime;

    }

    //状态取反

    self.isSelected = !self.isSelected;

    

    

    

}


- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    

    self.view.backgroundColor = [UIColor redColor];

    

    [self createButtView];

    

}


你可能感兴趣的:(ios)