網状に配置した四角の色をとびとびで変化させるiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
@interface ViewController ()
@property (nonatomic, strong) NSMutableArray *lines;
@property (nonatomic) int count;
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor colorWithWhite:0.1 alpha:1];
[self createLines];
[self createColorPallet];
}
– (void)createLines
{
self.lines = [NSMutableArray array];
int row = 7;
int col = 7;
float da = 22;
float db = da * 1.618;
for (int i=0; i< row*col; i++) {
float x = (i % col) * 40 + 40;
float y = (i / col) * 40 + 50;
BOOL vertical = (i % 2);
CALayer *l = [CALayer layer];
if (vertical) {
l.frame = CGRectMake(0, 0, da, db);
l.backgroundColor = [UIColor whiteColor].CGColor;
} else {
l.frame = CGRectMake(0, 0, db, da);
l.backgroundColor = [UIColor brownColor].CGColor;
}
l.position = CGPointMake(x, y);
[self.view.layer addSublayer:l];
[self.lines addObject:l];
}
}
– (void)createColorPallet
{
for (int i=0; i<10; i++) {
float x = i * 30 + 12;
float y = 360;
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(x, y, 25, 40);
UIColor *color = [UIColor colorWithHue:i * 0.1 saturation:0.7 brightness:0.5 alpha:1];
if (i==0) color = [UIColor whiteColor];
if (i==9) color = [UIColor blackColor];
[btn setBackgroundColor:color];
[btn setBackgroundImage:[self imageWithColor:color] forState:UIControlStateNormal];
[self.view addSubview:btn];
[btn addTarget:self action:@selector(tap:) forControlEvents:UIControlEventTouchUpInside];
}
}
– (void)tap:(UIButton *)sender
{
for (int i=0; i<self.lines.count; i++) {
float type = [self checkType:i];
if (type == self.count) {
CALayer *l = self.lines[i];
l.backgroundColor = sender.backgroundColor.CGColor;
}
}
self.count = (self.count + 1) % 4;
}
– (int)checkType:(int)n
{
int type = 0;
// typeA
if ((n%14) > 6 && (n % 2) == 0) {
type = 0;
} else if ((n%14) <= 6 && (n % 2) == 0) {
type = 1;
} else if ((n%14) > 6 && (n % 2) == 1) {
type = 2;
} else if ((n%14) <= 6 && (n % 2) == 1) {
type = 3;
}
return type;
}
– (UIImage *)imageWithColor:(UIColor *)color
{
CGRect rect = CGRectMake(0, 0, 1, 1);
UIGraphicsBeginImageContext(rect.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(ctx, color.CGColor);
CGContextFillRect(ctx, rect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
@end