下面的代码创建一个渐变 [从红色、黄色、绿色、蓝色、红色] 并在触摸它时返回 RGB 值。
下面的代码可用于任意数量的颜色,只需将它们的值设置为colors Array。
所选颜色设置为 selectedColorView(UIView) 的 backgroundColor。
ViewController.h 文件
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
ViewController.m 文件
#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>
@interface ViewController ()
@end
@implementation ViewController{
UIView *selectedColorView;
CAGradientLayer *layer;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
layer =[CAGradientLayer layer];
[layer setFrame:CGRectMake(20, 20, 280, 50)];
layer.colors =@[(id)[UIColor redColor].CGColor,(id)[UIColor yellowColor].CGColor,(id)[UIColor greenColor].CGColor,(id)[UIColor blueColor].CGColor,(id)[UIColor redColor].CGColor];
layer.startPoint =CGPointMake(0, .5);
layer.endPoint =CGPointMake(1, .5);
[self.view.layer addSublayer:layer];
selectedColorView =[[UIView alloc] initWithFrame:CGRectMake(20, 20+50, 280, 50)];
[self.view addSubview:selectedColorView];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
CGPoint p = [[touches anyObject] locationInView:self.view];
if(CGRectContainsPoint(layer.frame, p)){
CGFloat xOffset = (p.x - layer.frame.origin.x);
CGFloat gap=(layer.frame.size.width/(layer.colors.count-1));
NSInteger index = xOffset/gap;
xOffset =xOffset -index*gap;
UIColor *color1=[UIColor colorWithCGColor:(CGColorRef)layer.colors[index]];
UIColor *color2=[UIColor colorWithCGColor:(CGColorRef)layer.colors[index+1]];
CGFloat r1,g1,b1,a1,r2,g2,b2,a2;
[color1 getRed:&r1 green:&g1 blue:&b1 alpha:&a1];
[color2 getRed:&r2 green:&g2 blue:&b2 alpha:&a2];
selectedColorView.backgroundColor =[UIColor colorWithRed:(1-(xOffset/gap))*r1 +(xOffset/gap)*r2 green:(1-(xOffset/gap))*g1 +(xOffset/gap)*g2 blue:(1-(xOffset/gap))*b1 +(xOffset/gap)*b2 alpha:1.0];
}
}
@end