矢印でマスキングして遊んでみます。上半分が黒、下半分が白の画面でこの矢印マスクを上下に動かすようなiPhoneアプリを書いてみます。矢印と重なった部分の背景がくりぬかれるので、上が白、下が黒のViewを背景の下に配置して、重なった部分は白黒が反転するようにしています。
動作イメージ
XcodeからiOS6 iPhone Simulatorで動かすとこんな感じになります。
サンプルコード
#import “ViewController.h”
#import <QuartzCore/QuartzCore.h>
@interface ViewController () {
NSTimer *timer;
UIView *blackwhite;
UIView *whiteblack;
UIView *arrow;
}
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
[self createBlackWhiteWall];
[self createArrow];
[self start];
}
– (void)createBlackWhiteWall
{
blackwhite = [[UIView alloc] initWithFrame:self.view.bounds];
blackwhite.backgroundColor = [UIColor whiteColor];
CALayer *black = [CALayer layer];
black.frame = CGRectMake(0, 0, 320, 274);
black.backgroundColor = [UIColor blackColor].CGColor;
[blackwhite.layer addSublayer:black];
[self.view addSubview:blackwhite];
whiteblack = [[UIView alloc] initWithFrame:self.view.bounds];
whiteblack.backgroundColor = [UIColor blackColor];
CALayer *white = [CALayer layer];
white.frame = CGRectMake(0, 0, 320, 274);
white.backgroundColor = [UIColor whiteColor].CGColor;
[whiteblack.layer addSublayer:white];
[self.view addSubview:whiteblack];
}
– (UIView *)createArrow
{
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(30, 0)];
[path addLineToPoint:CGPointMake(0, 25)];
[path addLineToPoint:CGPointMake(15, 25)];
[path addLineToPoint:CGPointMake(15, 60)];
[path addLineToPoint:CGPointMake(45, 60)];
[path addLineToPoint:CGPointMake(45, 25)];
[path addLineToPoint:CGPointMake(60, 25)];
[path closePath];
CAShapeLayer *sl = [CAShapeLayer layer];
sl.fillColor = [UIColor blackColor].CGColor;
sl.path = path.CGPath;
sl.transform = CATransform3DMakeScale(2, 2, 1);
arrow = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 120, 120)];
[arrow.layer addSublayer:sl];
[self.view addSubview:arrow];
whiteblack.layer.mask = arrow.layer;
arrow.center = CGPointMake(150, 270);
return arrow;
}
– (void)start
{
[NSTimer scheduledTimerWithTimeInterval:1.0/60.0 target:self selector:@selector(tick:) userInfo:nil repeats:YES];
}
– (void)tick:(NSTimer*)sender
{
if (arrow.center.y < 50) {
arrow.tag = 1;
arrow.transform = CGAffineTransformMakeRotation(M_PI);
} else if (arrow.center.y > 500) {
arrow.tag = 2;
arrow.transform = CGAffineTransformIdentity;
}
float velocity = –2;
if (arrow.tag == 1) {
velocity = 2;
}
arrow.center = CGPointMake(arrow.center.x, arrow.center.y + velocity);
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end