近期某設(shè)計師喜歡上了用漸變色的背景.
發(fā)現(xiàn)Pokemon Go當(dāng)中也使用了很多漸變色,覺得很喜歡Pokemon Go的UI設(shè)計.
漸變有線性漸變和徑向漸變,在iOS中實現(xiàn)漸變色可以用CAGradientLayer,或者用Quartz2D(平臺:Xcode7.2/iOS9.2).
-
1.使用CAGradientLayer實現(xiàn)線性漸變
直接上代碼:
CAGradientLayer *layer = [CAGradientLayer layer];
layer.frame = self.view.bounds;
//顏色分配:四個一組代表一種顏色(r,g,b,a)
layer.colors = @[(__bridge id) [UIColor colorWithRed:55/255.0 green:222/255.0 blue:255/255.0 alpha:1.0].CGColor,
(__bridge id) [UIColor colorWithRed:57/255.0 green:169/255.0 blue:213/255.0 alpha:1.0].CGColor];
//起始點
layer.startPoint = CGPointMake(0.5, 0.25);
//結(jié)束點
layer.endPoint = CGPointMake(0.5, 0.75);[self.view.layer addSublayer:layer];
對于起始點和結(jié)束點(0,0)為左下,(1,1)為右上.
實際效果是這樣的
-
2.使用Quartz2D實現(xiàn)徑向漸變
上代碼:
//新建子類,繼承UIVIew
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();//1.Create CGColorSpaceRef CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); //2.Create CGGradientRef //顏色分配:四個一組代表一種顏色(r,g,b,a) CGFloat components[8] = {55/255.0, 222/255.0, 255/255.0, 1.0, 57/255.0, 169/255.0 ,213/255.0, 1.0}; //位置:每種顏色對應(yīng)中心點位置,取0-1之間的float,默認(rèn)起始點為(0,0) CGFloat locations[2] = {0, 1}; //點數(shù)量:count為locations數(shù)量,size_t類型 size_t count = 2; CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, count); //3.DrawRadialGradient /**漸變點: 起始點 結(jié)束點 起始半徑 結(jié)束半徑 */ CGPoint startCenter = CGPointMake(self.frame.size.width * 0.5, self.frame.size.height * 0.25); CGPoint endCenter = CGPointMake(self.frame.size.width * 0.5, self.frame.size.height * 0.25); CGFloat startRadius = 0; CGFloat endRadius = self.frame.size.height; CGContextDrawRadialGradient(context, gradient, startCenter, startRadius, endCenter, endRadius, kCGGradientDrawsAfterEndLocation); //4.Release CGColorSpaceRelease(colorSpace); colorSpace = NULL; CGGradientRelease(gradient); gradient = NULL; }
放效果圖:
用Quartz2D也可以實現(xiàn)線性漸變,方法類似.
由于筆者知識有限喷橙,如有錯誤抖锥,歡迎指出蜂莉。