UISliderを使ってRGBカラーを表示するプログラム
UISliderを3つ使って、RGBカラーを表示するプログラムを作りました。
// ViewController.h #import <UIKit/UIKit.h> #import "MyView.h" @interface ViewController : UIViewController { MyView* _myView; UISlider* _sliderR; UISlider* _sliderG; UISlider* _sliderB; } @end
// ViewController.m #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. _myView = [[MyView alloc] init]; _myView.frame = CGRectMake(10, 10, 300, 200); [self.view addSubview:_myView]; _sliderR = [[UISlider alloc] init]; _sliderR.frame = CGRectMake(10, 300, 300, 40); _sliderR.minimumValue = 0; _sliderR.maximumValue = 255; [_sliderR addTarget:self action:@selector(sliderDidChange:) forControlEvents:UIControlEventValueChanged]; [self.view addSubview:_sliderR]; _sliderG = [[UISlider alloc] init]; _sliderG.frame = CGRectMake(10, 340, 300, 40); _sliderG.minimumValue = 0; _sliderG.maximumValue = 255; [_sliderG addTarget:self action:@selector(sliderDidChange:) forControlEvents:UIControlEventValueChanged]; [self.view addSubview:_sliderG]; _sliderB = [[UISlider alloc] init]; _sliderB.frame = CGRectMake(10, 380, 300, 40); _sliderB.minimumValue = 0; _sliderB.maximumValue = 255; [_sliderB addTarget:self action:@selector(sliderDidChange:) forControlEvents:UIControlEventValueChanged]; [self.view addSubview:_sliderB]; } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) { return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } else { return YES; } } - (void)sliderDidChange:(id)sender { [_myView setR:_sliderR.value g:_sliderG.value b:_sliderB.value]; } @end
// MyView.h #import <UIKit/UIKit.h> @interface MyView : UIView { int _r; int _g; int _b; } - (void)setR:(int)r g:(int)g b:(int)b; @end
// MyView.m #import "MyView.h" @implementation MyView - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { _r = _g = _b = 0; } return self; } // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. - (void)drawRect:(CGRect)rect { CGContextRef c = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(c, [UIColor colorWithRed:_r/255.0 green:_g/255.0 blue:_b/255.0 alpha:1.0].CGColor); CGContextFillRect(c, [self bounds]); } - (void)setR:(int)r g:(int)g b:(int)b { _r = r; _g = g; _b = b; [self setNeedsDisplay]; } @end