色の付いた枠で囲んだドットの色を変えるiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
@interface ViewController ()
@property (nonatomic, weak) UIView *selected;
@property (nonatomic, strong) NSMutableArray *dots;
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
[self createDots];
[self createColorFrameRGB];
}
– (void)createDots
{
self.dots = [NSMutableArray array];
for (int i=0; i<400; i++) {
float x = (i % 20) * 15 + 12.5;
float y = (i / 20) * 15 + 50;
CALayer *dot = [CALayer layer];
dot.frame = CGRectMake(x, y, 10, 10);
dot.backgroundColor = [UIColor lightGrayColor].CGColor;
dot.cornerRadius = 5;
[self.view.layer addSublayer:dot];
[self.dots addObject:dot];
}
}
– (void)createColorFrameRGB
{
for (int i=0; i<3; i++) {
float x = i * 100 + 10;
float y = 370;
UIView *colorFrame = [[UIView alloc] initWithFrame:CGRectMake(x, y, 100, 100)];
colorFrame.tag = 1;
colorFrame.layer.borderWidth = 3;
switch (i) {
case 0:
colorFrame.layer.borderColor = [UIColor colorWithRed:0.8 green:0 blue:0 alpha:1].CGColor;
break;
case 1:
colorFrame.layer.borderColor = [UIColor colorWithRed:0 green:0.8 blue:0 alpha:1].CGColor;
break;
case 2:
colorFrame.layer.borderColor = [UIColor colorWithRed:0 green:0 blue:0.8 alpha:1].CGColor;
break;
default:
break;
}
[self.view addSubview:colorFrame];
}
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInView:self.view];
UIView *hit = [self.view hitTest:p withEvent:nil];
if (hit.tag == 1) {
self.selected = hit;
}
}
– (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if (self.selected) {
CGPoint p = [[touches anyObject] locationInView:self.view];
self.selected.center = p;
[self updateDotColor];
}
}
– (void)updateDotColor
{
NSPredicate *pred = [NSPredicate predicateWithFormat:@”tag == 1″];
NSArray *colorFrames = [self.view.subviews filteredArrayUsingPredicate:pred];
for (CALayer *dot in self.dots) {
NSMutableArray *arr = [NSMutableArray array];
for (UIView *f in colorFrames) {
if (CGRectContainsPoint(f.frame, dot.position)) {
[arr addObject:f];
}
}
if (arr.count > 0) {
dot.backgroundColor = [self colorFromArr:arr];
} else {
dot.backgroundColor = [UIColor lightGrayColor].CGColor;
}
}
}
– (CGColorRef)colorFromArr:(NSArray *)colorViews
{
float red = 0;
float green = 0;
float blue = 0;
for (UIView *f in colorViews) {
const CGFloat *components = CGColorGetComponents(f.layer.borderColor);
CGFloat r = components[0];
CGFloat g = components[1];
CGFloat b = components[2];
if (r > 0) red += r;
if (g > 0) green += g;
if (b > 0) blue += b;
}
return [UIColor colorWithRed:red green:green blue:blue alpha:1].CGColor;
}
@end