UIImageView の画像をタップでくるっと変える方法のメモ

ポイント

・CATransform3DMakeRotation

・90度まわしたところで画像を切り替え、

 バックグラウンドで270度までまわすことで、

 イメージが反転表示されないようにする

クルットまわして、コレを入れ替える

表ー裏の回転をさせるサンプルコード

※Quartzを利用するので、追加しておく

#import “ViewController.h”

#import <QuartzCore/QuartzCore.h>

@interface ViewController ()

@property (nonatomic, strong) UIImageView *imageView;

@end

@implementation ViewController

@synthesize imageView;

– (void)viewDidLoad

{

    [super viewDidLoad];

    

    self.imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@”front.png”]];

    imageView.bounds = CGRectMake(0, 0, 250, 250);

    imageView.center = self.view.center;

    [self.view addSubview:self.imageView];

}

static BOOL front = true; // 表裏のフラグ

– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    

    [UIView animateWithDuration:0.5 animations:^{

        // 90度まで回転

        self.imageView.layer.transform = CATransform3DMakeRotation(M_PI * 0.5, 0.0f, 1.0f, 0.0f);

    } completion:^(BOOL finished) {

        

        // 270までアニメ無しで進める

        self.imageView.layer.transform = CATransform3DMakeRotation(M_PI * 1.5, 0.0f, 1.0f, 0.0f);

        

        // 絵をすり替え

        self.imageView.image = front ? [UIImage imageNamed:@”back.png”] : [UIImage imageNamed:@”front.png”];

        

        // 360度まで回転

        [UIView animateWithDuration:0.5 animations:^{

            self.imageView.layer.transform = CATransform3DMakeRotation(M_PI * 2, 0.0f, 1.0f, 0.0f);

        } completion:^(BOOL finished) {

            front = !front;

        }];

    }];

}

@end