近期某设计师喜欢上了用渐变色的背景.
发现Pokemon Go当中也使用了很多渐变色,觉得很喜欢Pokemon Go的UI设计.
渐变有线性渐变和径向渐变,在iOS中实现渐变色可以用CAGradientLayer,或者用Quartz2D(平台:Xcode7.2/iOS9.2).
-
1.使用CAGradientLayer实现线性渐变
直接上代码:
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);
//结束点
layer.endPoint = CGPointMake(0.5, 0.75);[self.view.layer addSublayer:layer];
对于起始点和结束点(0,0)为左下,(1,1)为右上.
实际效果是这样的
-
2.使用Quartz2D实现径向渐变
上代码:
//新建子类,继承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}; //位置:每种颜色对应中心点位置,取0-1之间的float,默认起始点为(0,0) CGFloat locations[2] = {0, 1}; //点数量:count为locations数量,size_t类型 size_t count = 2; CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, count); //3.DrawRadialGradient /**渐变点: 起始点 结束点 起始半径 结束半径 */ 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也可以实现线性渐变,方法类似.
由于笔者知识有限,如有错误,欢迎指出。