iOS实现渐变色背景(两种方式实现)
之前做过类似的功能,现在记录一下,来来来。。。
效果图:
说明===========================
方法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,//从左到右 };