之前做過類似的功能,現在記錄一下,來來來。。。
效果圖:

說明===========================
方法1:
說明:無返回值
用法:直接調用方法。原理是在view的layer層添加。
方法2:
說明:先返回一個Image,再使用
用法:若是image背景,直接使用,若是color背景,用 [UIColor colorWithPatternImage:image]即可。
代碼===========================
方法1:
-(void)createByCAGradientLayer:(UIColor *)startColor endColor:(UIColor *)endColor layerFrame:(CGRect)frame direction:(GradientType)direction{
CAGradientLayer *layer = [CAGradientLayer new];
//存放漸變的顏色的數組
layer.colors = @[(__bridge id)startColor.CGColor, (__bridge id)endColor.CGColor];
//起點和終點表示的坐標系位置,(0,0)表示左上角,(1,1)表示右下角
switch (direction) {
case GradientTypeTopToBottom:
layer.startPoint = CGPointMake(0.0, 0.0);
layer.endPoint = CGPointMake(0.0, 1);
break;
case GradientTypeLeftToRight:
layer.startPoint = CGPointMake(0.0, 0.0);
layer.endPoint = CGPointMake(1, 0.0);
break;
default:
break;
}
layer.frame = frame;
[self.view.layer addSublayer:layer];
}
方法2:
- (UIImage *)getGradientImageFromColors:(NSArray*)colors gradientType:(GradientType)gradientType imgSize:(CGSize)imgSize {
NSMutableArray *ar = [NSMutableArray array];
for(UIColor *c in colors) {
[ar addObject:(id)c.CGColor];
}
UIGraphicsBeginImageContextWithOptions(imgSize, 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 GradientTypeTopToBottom:
start = CGPointMake(0.0, 0.0);
end = CGPointMake(0.0, imgSize.height);
break;
case GradientTypeLeftToRight:
start = CGPointMake(0.0, 0.0);
end = CGPointMake(imgSize.width, 0.0);
break;
default:
break;
}
CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
CGGradientRelease(gradient);
CGContextRestoreGState(context);
CGColorSpaceRelease(colorSpace);
UIGraphicsEndImageContext();
return image;
}
這里有個方向枚舉,用來表示垂直還是水平
typedef NS_ENUM(NSUInteger, GradientType) {
GradientTypeTopToBottom = 0,//從上到下
GradientTypeLeftToRight = 1,//從左到右
};
