iOS view 颜色渐变

//渐变色过渡自然

        CAGradientLayer *layer = [CAGradientLayer layer];

        layer.frame = CGRectMake(0, 0, curW-10,44);

        layer.colors = [NSArray arrayWithObjects:(id)[UIColor clearColor].CGColor, (id)[UIColor grayColor].CGColor, nil];

        for (CALayer *sublayer in [self.bgView.layer sublayers])

        {

            [sublayer removeFromSuperlayer];

        }

        [self.bgView.layer insertSublayer:layer atIndex:0];

 

 

 

//返回渐变的image

- (UIImage*) gradientImageFromColors:(NSArray*)colors ByGradientType:(GradientType)gradientType inSize:(CGSize)size{
NSMutableArray *ar = [NSMutableArray array];
for(UIColor *c in colors) {
[ar addObject:(id)c.CGColor];
}
UIGraphicsBeginImageContextWithOptions(size, YES, 1);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)ar, NULL);
CGPoint start;
CGPoint end;
switch (gradientType) {
//上下渐变
case 0:
start = CGPointMake(0.0, 0.0);
end = CGPointMake(0.0, size.height);
break;
case 1:
//左右渐变
start = CGPointMake(0.0, 0.0);
end = CGPointMake(size.width, 0.0);
break;
case 2:
//对角两侧渐变
start = CGPointMake(0.0, 0.0);
end = CGPointMake(size.width, size.height);
break;
case 3:
//对角两侧渐变
start = CGPointMake(size.width, 0.0);
end = CGPointMake(0.0, size.height);
break;
case 4:
//线性渐变
start = CGPointMake(size.width/2, size.height/2);
end = CGPointMake(size.width/2, size.height/2);
break;
default:
break;
}
CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);

if (gradientType == 4) {
CGContextDrawRadialGradient(context, gradient, start, 10, end, size.width/3, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);

}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
CGGradientRelease(gradient);
CGContextRestoreGState(context);
CGColorSpaceRelease(colorSpace);
UIGraphicsEndImageContext();
return image;
}

你可能感兴趣的:(view)