给UIView控件换成渐变色
2021-03-18 本文已影响0人
黎先生_
需求:给UIView控件换成渐变色(UILabel、UIButton、UIView)
#pragma mark view添加字体渐变色
+ (UIColor *)addGradientToView:(UIView *)view withColorArr:(NSArray *)colorArr
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, [UIScreen mainScreen].scale);
CGContextRef context = UIGraphicsGetCurrentContext();
//绘制渐变层
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradientRef = CGGradientCreateWithColors(colorSpaceRef,
(__bridge CFArrayRef)colorArr,
NULL);
CGPoint startPoint = CGPointZero;
CGPoint endPoint = CGPointMake(CGRectGetMaxX(view.bounds), CGRectGetMaxY(view.bounds));
CGContextDrawLinearGradient(context, gradientRef, startPoint, endPoint, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
//取到渐变图片
UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
//释放资源
CGColorSpaceRelease(colorSpaceRef);
CGGradientRelease(gradientRef);
UIGraphicsEndImageContext();
return [UIColor colorWithPatternImage:gradientImage];
}