1.设置view的渐变色
- (void)setGradient:(CGRect)frame view:(UIView *)view{
// 创建 CAGradientLayer 对象
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
// 设置 gradientLayer 的 Frame
gradientLayer.frame = frame;
// 创建渐变色数组,需要转换为CGColor颜色
UIColor * color1 = nil;
UIColor * color2 = nil;
color1 = [UIColor colorWithRed:21/255.0 green:126/255.0 blue:251/255.0 alpha:1.0];
color2 = [UIColor colorWithRed:54/255.0 green:188/255.0 blue:153/255.0 alpha:1.0];
gradientLayer.colors = @[(id)color1.CGColor,
(id)color2.CGColor];
// 设置颜色变化点,取值范围 0.0~1.0
// gradientLayer.locations = @[@0 ,@1];
// 设置渐变颜色方向,左上点为(0,0), 右下点为(1,1)
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint = CGPointMake(0, 1);
// 添加渐变色到创建的 UIView 上去
[view.layer addSublayer:gradientLayer];
}
2.制作一张带有渐变色的image
- (UIImage *)p_gradientFrame:(CGRect)frame
{
//底部上下渐变效果背景
//通过图片上下文设置颜色空间间
UIGraphicsBeginImageContext(frame.size);
//获得当前的上下文
CGContextRef context = UIGraphicsGetCurrentContext();
//创建颜色空间 /* Create a DeviceRGB color space. */
CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
//通过矩阵调整空间变换
CGContextScaleCTM(context, frame.size.width, frame.size.height);
//通过颜色组件获得渐变上下文
CGGradientRef backGradient;
CGFloat colors[] = {
83/255.0, 178/255.0, 253/255.0, 1.0,
41/255.0, 123/255.0, 251/255.0, 1.0,
};
backGradient = CGGradientCreateWithColorComponents(rgb, colors, NULL, sizeof(colors)/(sizeof(colors[0])*4));
//释放颜色渐变
CGColorSpaceRelease(rgb);
//通过上下文绘画线色渐变
//设置渐变颜色方向,左上点为(0,0), 右下点为(1,1)
CGContextDrawLinearGradient(context, backGradient, CGPointMake(0, 0.5), CGPointMake(1, 0.5), kCGGradientDrawsBeforeStartLocation);
//通过图片上下文获得照片
return UIGraphicsGetImageFromCurrentImageContext();
}
网友评论