シマシマをくるっと線で囲んで、お絵描きをしていくiPhoneアプリを書いてみます。囲まれたところのシマを一本分ずらすことで、そこに何かがあるような錯覚効果を利用。
動作イメージ
XcodeからiOS6 iPhone Simulatorで動かすとこんな感じになります。
サンプルコード
#import “ViewController.h”
#import <QuartzCore/QuartzCore.h>
@interface ViewController ()
{
UIView *stripes;
UIBezierPath *path;
CAShapeLayer *sl;
}
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
[self createStripes];
}
– (void)createStripes
{
stripes = [[UIView alloc] initWithFrame:self.view.bounds];
stripes.backgroundColor = [self color:3];
[self.view addSubview:stripes];
float w = 20;
for (int i=0; i<320/w; i++) {
float x = i * w * 2.0 – w/2.0;
UIView *stripe = [[UIView alloc] initWithFrame:CGRectMake(x, 0, w, 568)];
stripe.backgroundColor = [self color:4];
[stripes addSubview:stripe];
}
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[sl removeFromSuperlayer];
CGPoint p = [[touches anyObject] locationInView:self.view];
path = [UIBezierPath bezierPath];
[path moveToPoint:p];
sl = [CAShapeLayer layer];
sl.fillColor = [UIColor clearColor].CGColor;
sl.strokeColor = [self color:1].CGColor;
sl.lineWidth = 5;
[self.view.layer addSublayer:sl];
}
– (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInView:self.view];
[path addLineToPoint:p];
sl.path = path.CGPath;
}
– (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UIView *v = [self copyImage];
CAShapeLayer *mask = [CAShapeLayer layer];
mask.position = CGPointMake(mask.position.x–20, mask.position.y);
mask.fillColor = [UIColor blackColor].CGColor;
mask.path = path.CGPath;
v.layer.mask = mask;
v.center = CGPointMake(v.center.x+20, v.center.y);
[self.view addSubview:v];
}
– (UIView *)copyImage
{
UIGraphicsBeginImageContext(self.view.frame.size);
[stripes.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *iv = [[UIImageView alloc] initWithImage:outputImage];
return iv;
}
#define UIColorHex(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
– (UIColor*)color:(int)i
{
switch (i) {
case 0:
return UIColorHex(0xD89845);
case 1:
return UIColorHex(0xF5DFAB);
case 2:
return UIColorHex(0x58B5AB);
case 3:
return UIColorHex(0x2B1F1D);
case 4:
return UIColorHex(0xFC6955);
default:
break;
}
return nil;
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end