カラーホイールでtriadになる3色をUIColorで作成する方法のメモ
(XcodeのiOS6 Simulatorで試しています。)
ポイント
・red blue greenの値を横滑りさせる
サンプルコード
[ColorManagerKun.h]
@interface ColorManagerKun : NSObject
+ (NSArray*)triad:(UIColor*)selected;
@end
[ColorManagerKun.m]
@implementation ColorManagerKun
+ (NSArray *)triad:(UIColor *)color
{
CGFloat red = 0.0, green = 0.0, blue = 0.0, alpha = 0.0;
// 指定したColorの red green blueを取得する
if ([color respondsToSelector:@selector(getRed:green:blue:alpha:)]) {
[color getRed:&red green:&green blue:&blue alpha:&alpha];
} else {
const CGFloat *components = CGColorGetComponents(color.CGColor);
red = components[0];
green = components[1];
blue = components[2];
alpha = components[3];
}
// カラーホイールのtriad
UIColor *second = [UIColor colorWithRed:green green:blue blue:red alpha:alpha];
UIColor *third = [UIColor colorWithRed:blue green:red blue:green alpha:alpha];
return [[NSArray alloc] initWithObjects:color, second, third, nil];
}
@end
表示用にViewController.mに実装
[ViewController.m]
#import “ViewController.h”
#import “ColorManagerKun.h”
#import <QuartzCore/QuartzCore.h>
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
// triadを配列で
NSArray *triad = [ColorManagerKun triad:[UIColor redColor]];
//三角形中心
CGPoint vertex0 = CGPointMake(150, 150);
for (int i = 0; i < [triad count]; i++) {
float r = 2 * M_PI / 3;
CGPoint vertex = CGPointMake(vertex0.x + 50 * sin(r * i), vertex0.y + 50 * cos(r * i));
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
view.center = vertex;
view.backgroundColor = [triad objectAtIndex:i];
view.layer.cornerRadius = 15.0;
[self.view addSubview:view];
}
// 円のガイドをライトグレーで
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
view.center = vertex0;
view.layer.cornerRadius = 50.0;
view.layer.borderWidth = 1.0;
view.layer.borderColor = [UIColor lightGrayColor].CGColor;
view.backgroundColor = [UIColor clearColor];
[self.view addSubview:view];
// 他の色、黄色、紫、水色
triad = [ColorManagerKun triad:[UIColor yellowColor]];
for (int i = 0; i < [triad count]; i++) {
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(30, 30 * (i + 1), 20, 20)];
view.backgroundColor = [triad objectAtIndex:i];
[self.view addSubview:view];
}
}
@end