渐变色可以作为视频的图片的placeholderImage,方便字体的显示,用代码生成layer层减少内存的消耗。
CAGradientLayer+NIPExtension.h
#import <QuartzCore/QuartzCore.h>
@interface CAGradientLayer (NIPExtension)
/**
* 生成一个渐变色的layer
*
* @param frame layer的尺寸
* @param startPoint 渐变色的起始位置(范围:0-1)
* @param endPoint 渐变色的终止位置(范围:0-1)
* @param colors 颜色数组
* @param locations 颜色分割点 (范围:0-1)
*
* @return 返回一个渐变色layer
*/
+ (instancetype)gradientLayerWithFrame:(CGRect)frame startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint colors:(NSArray<UIColor *>*)colors locations:(NSArray*)locations;
@end
CAGradientLayer+NIPExtension.m
#import "CAGradientLayer+NIPExtension.h"
@implementation CAGradientLayer (NIPExtension)
+ (instancetype)gradientLayerWithFrame:(CGRect)frame startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint colors:(NSArray<UIColor *> *)colors locations:(NSArray *)locations
{
// 生成一个渐变色的layer
CAGradientLayer * layer = [CAGradientLayer layer];
// 设置尺寸
layer.frame = frame;
// 渐变色区域的开始位置(位置范围 0 - 1)
layer.startPoint = startPoint;
// 渐变色区域的结束位置
layer.endPoint = endPoint;
// 设置颜色数组
NSMutableArray * colorRefs = [NSMutableArray array];
for (UIColor *color in colors) {
[colorRefs addObject:(__bridge id)color.CGColor];
}
layer.colors = colorRefs;
// 设置颜色的分割点(范围:0-1)
layer.locations = locations;
return layer;
}
@end
补上效果图:
补充:
线性渐变和径向渐变
- (void)drawLineGradientView{
// 1.创建颜色空间
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
// 2.创建渐变色
CGFloat components[8] = {229/255.0,77/255.0,65/255.0,1.0,
236/255.0,116/255.0,79/255.0,1.0};
// CGFloat locations[2] = {0.5,0.9};
CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace,
components,
NULL,
2);
// 3.设置剪裁区域
CGRect rect = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
CGContextClipToRect(UIGraphicsGetCurrentContext(), rect);
// 4.绘制渐变色
CGContextDrawLinearGradient(UIGraphicsGetCurrentContext(),
gradient,
CGPointMake(0, 0),
CGPointMake(0, self.frame.size.height),
kCGGradientDrawsAfterEndLocation|kCGGradientDrawsBeforeStartLocation);
// 释放对象
CGColorSpaceRelease(colorSpace);
CGGradientRelease(gradient);
}
径向渐变
- (void)drawRadialGradientView{
// 1、创建颜色空间
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
// 2、创建渐变色
CGFloat components[8] = {236/255.0,116/255.0,79/255.0,1.0,224/255.0,77/255.0,68/255.0,1.0};
// CGFloat locations[2] = {0.3,1.0};
CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace,
components,
NULL,
2);
// 3、绘制渐变色
CGContextDrawRadialGradient(UIGraphicsGetCurrentContext(),
gradient,
CGPointMake(self.center.x, self.center.y),
0,
CGPointMake(self.center.x, self.center.y),
160,
kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
// 4、释放对象
CGColorSpaceRelease(colorSpace);
CGGradientRelease(gradient);
}