代码让UIImage具有渐变效果

本文介绍了一个UIImage的category,通过自定义方法实现为图片添加背景颜色、阴影及模糊效果。使用CGColor和CGGradient创建渐变背景,并利用Core Graphics进行绘制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

做一个UIImage的category,直接上代码:

- (UIImage *) imageWithBackgroundColor:(UIColor *)bgColor shadeAlpha1:(CGFloat)alpha1 shadeAlpha2:(CGFloat)alpha2 shadeAlpha3:(CGFloat)alpha3 shadowColor:(UIColor *)shadowColor shadowOffset:(CGSize)shadowOffset shadowBlur:(CGFloat)shadowBlur { UIImage *image = self; CGColorRef cgColor = [bgColor CGColor]; CGColorRef cgShadowColor = [shadowColor CGColor]; CGFloat components[16] = {1,1,1,alpha1,1,1,1,alpha1,1,1,1,alpha2,1,1,1,alpha3}; CGFloat locations[4] = {0,0.5,0.6,1}; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGGradientRef colorGradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, (size_t)4); CGRect contextRect; contextRect.origin.x = 0.0f; contextRect.origin.y = 0.0f; contextRect.size = [image size]; //contextRect.size = CGSizeMake([image size].width+5,[image size].height+5); // Retrieve source image and begin image context UIImage *itemImage = image; CGSize itemImageSize = [itemImage size]; CGPoint itemImagePosition; itemImagePosition.x = ceilf((contextRect.size.width - itemImageSize.width) / 2); itemImagePosition.y = ceilf((contextRect.size.height - itemImageSize.height) / 2); UIGraphicsBeginImageContext(contextRect.size); CGContextRef c = UIGraphicsGetCurrentContext(); // Setup shadow CGContextSetShadowWithColor(c, shadowOffset, shadowBlur, cgShadowColor); // Setup transparency layer and clip to mask CGContextBeginTransparencyLayer(c, NULL); CGContextScaleCTM(c, 1.0, -1.0); CGContextClipToMask(c, CGRectMake(itemImagePosition.x, -itemImagePosition.y, itemImageSize.width, -itemImageSize.height), [itemImage CGImage]); // Fill and end the transparency layer CGContextSetFillColorWithColor(c, cgColor); contextRect.size.height = -contextRect.size.height; CGContextFillRect(c, contextRect); CGContextDrawLinearGradient(c, colorGradient,CGPointZero,CGPointMake(contextRect.size.width*1.0/4.0,contextRect.size.height),0); CGContextEndTransparencyLayer(c); //CGPointMake(contextRect.size.width*3.0/4.0, 0) // Set selected image and end context UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); CGColorSpaceRelease(colorSpace); CGGradientRelease(colorGradient); return resultImage; }

用法如下:

UIImage *niceImage = [[UIImage imageNamed:@"image_name"] imageWithBackgroundColor:[UIColor colorWithRed:41.0/255.0 green:147.0/255.0 blue:239.0/255.0 alpha:1.0] shadeAlpha1:0.6 shadeAlpha2:0.0 shadeAlpha3:0.4 shadowColor:[UIColor blackColor] shadowOffset:CGSizeMake(0.0f, -1.0f) shadowBlur:3.0];

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值