美文网首页
让图片转起来

让图片转起来

作者: shushuzhen | 来源:发表于2017-03-28 17:38 被阅读70次

    先上一个gif图,看下效果:



    在项目中很少用到动画,这个动画可以用于更新或者下载或者操作等待时的动画。
    下面直接上代码:

    #import "ViewController.h"
    
    @interface ViewController ()
    @property (nonatomic, strong) UIImageView *imageV;
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        // 创建一个ImageView
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
        imageView.center = self.view.center;
        imageView.image = [UIImage imageNamed:@"airCon_on"];
        [self.view addSubview:imageView];
        self.imageV = imageView;
        
        // 创建一个点击按钮
        UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [clickBtn setFrame:CGRectMake(0, 0, 100, 50)];
        clickBtn.center = CGPointMake(imageView.center.x, 100);
        [clickBtn setTitle:@"点这里呀" forState:UIControlStateNormal];
        clickBtn.titleLabel.font = [UIFont systemFontOfSize:20];
        [clickBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [clickBtn addTarget:self action:@selector(clickToRotate:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:clickBtn];
    
    }
    
    - (void)clickToRotate:(UIButton *)btn{
    
        if (btn.selected) {
            // 启动旋转动画
           [self rotate360DegreeWithView:self.imageV];
        }else{
            // 移除旋转动画
            [self removreAnimation];
        }
        btn.selected = !btn.selected;
    }
    // 旋转动画
    - (void)rotate360DegreeWithView:(UIView *)view{
    
    
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
        animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
        
        // 围绕Z轴旋转,垂直于屏幕
        animation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(M_PI, 0.0, 0.0, 1.0)];
        // 旋转持续时间
        animation.duration = 0.5;
        // 旋转效果累计,先转180度,接着再旋转180度,从而实现360度旋转
        animation.cumulative = YES;
        // 旋转次数累计
        animation.repeatCount = 1000;
        view.tag = 1000;
        // 动画要加到layer上
        [view.layer addAnimation:animation forKey:nil];
    }
    // 移除动画
    - (void)removreAnimation{
      
        UIView *view = [self.view viewWithTag:1000];
        [view.layer removeAllAnimations];
    }
    @end
    

    动画要加到view的layer上面

    相关文章

      网友评论

          本文标题:让图片转起来

          本文链接:https://www.haomeiwen.com/subject/qmajottx.html