iOS Core Graphics中有两个方法用于绘制渐变颜色,CGContextDrawLinearGradient可以用于生成线性渐变,CGContextDrawRadialGradient用于生成圆半径方向颜色渐变。函数可以自定义path,无论是什么形状都可以,原理都是用来做Clip,所以需要在CGContextClip函数前调用CGContextAddPath函数把CGPathRef加入到Context中。
另外一个需要注意的地方是渐变的方向,方向是由两个点控制的,点的单位就是坐标。因此需要正确从CGPathRef中找到正确的点,方法当然有很多种看具体实现,本例中,我就是简单得通过调用CGPathGetBoundingBox函数,返回CGPathRef的矩形区域,然后根据这个矩形取两个点,读者可以根据自行需求修改具体代码。
- (void)viewDidLoad{
//创建view,并设置该view背景渐变
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth - 100, kScreenHeight- 180 - 170)];
[self addImgView:view];
view.layer.masksToBounds = YES;
view.layer.cornerRadius = 8;
}
- (void)drawLinearGradient:(CGContextRef)context
path:(CGPathRef)path
startColor:(CGColorRef)startColor
endColor:(CGColorRef)endColor
{
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat locations[] = { 0.0, 1.0 };
NSArray *colors = @[(__bridge id) startColor, (__bridge id) endColor];
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);
CGRect pathRect = CGPathGetBoundingBox(path);
//具体方向可根据需求修改
CGPoint startPoint = CGPointMake(CGRectGetMinX(pathRect), CGRectGetMinY(pathRect));
CGPoint endPoint = CGPointMake(CGRectGetMinX(pathRect), CGRectGetMaxY(pathRect));
CGContextSaveGState(context);
CGContextAddPath(context, path);
CGContextClip(context);
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGContextRestoreGState(context);
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);
}
- (UIView *)addImgView:(UIView *)view
{
//创建CGContextRef
UIGraphicsBeginImageContext(view.bounds.size);
CGContextRef gc = UIGraphicsGetCurrentContext();
//创建CGMutablePathRef
CGMutablePathRef path = CGPathCreateMutable();
//绘制Path
CGRect rect = CGRectMake(0, 0, view.width, view.height);
//矩形区域
CGPathAddRect(path, NULL, rect);
CGPathCloseSubpath(path);
//绘制渐变
[self drawLinearGradient:gc path:path startColor:[UIColor whiteColor].CGColor endColor:[UIColor colorWithRed:255.0/255.0 green:230.0/255.0 blue:230.0/255.0 alpha:1.0].CGColor];
//注意释放CGMutablePathRef
CGPathRelease(path);
//从Context中获取图像,并显示在界面上
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
[view addSubview:imgView];
return view;
}
网友评论