画面の左側にある、白い四角と、丸をゆびで動かしてみると
右側にある、四角と丸もうごくよ!
真ん中にもってくと、あれ、消えちゃった。
という感じの、iPhoneゲームのサンプルを描いてみた。
ポイント
左半分と、右半分のUIViewを用意します、この際に右側のlayerを
y軸周りに90度回転させることで鏡の世界のようにしてみました。
あとは、ImageContextを利用して、
左Viewに表示されているものを、そのまま右のViewにコピーしています。
環境
今回つくったiPhoneアプリサンプルは、
XcodeのiOS6 iPhone Simulatorで動かしています。
サンプルコード
#import “ViewController.h”
#import <QuartzCore/QuartzCore.h>
@interface ViewController() {
UIView *mirror;
}
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor blackColor];
UIView *from = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 160, 500)];
from.layer.masksToBounds = YES;
[self.view addSubview:from];
mirror = [[UIView alloc] initWithFrame:CGRectMake(160, 0, 160, 500)];
mirror.layer.transform = CATransform3DMakeRotation(M_PI, 0, 1, 0);
[self.view addSubview:mirror];
UIView *rect = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
rect.backgroundColor = [UIColor whiteColor];
[from addSubview:rect];
UIView *circle = [[UIView alloc] initWithFrame:CGRectMake(0, 300, 50, 50)];
circle.backgroundColor = [UIColor whiteColor];
circle.layer.cornerRadius = 25;
[from addSubview:circle];
UIView *line = [[UIView alloc] initWithFrame:CGRectMake(159.5, 0, 1, 500)];
line.backgroundColor = [UIColor darkGrayColor];
[self.view addSubview:line];
NSArray *parts = [NSArray arrayWithObjects:rect, circle, nil];
for (UIView *v in parts) {
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[v addGestureRecognizer:pan];
}
[self copyImageFrom:from to:mirror];
}
– (void)pan:(UIPanGestureRecognizer*)gr
{
gr.view.center = [gr locationInView:self.view];
[self copyImageFrom:gr.view.superview to:mirror];
}
– (void)copyImageFrom:(UIView*)from to:(UIView*)to
{
UIGraphicsBeginImageContext([from.layer frame].size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[from.layer renderInContext:UIGraphicsGetCurrentContext()];
to.layer.contents = (id)UIGraphicsGetImageFromCurrentImageContext().CGImage;
CGContextRelease(ctx);
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end