做一个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];
-
-
- 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();
-
- CGContextSetShadowWithColor(c, shadowOffset, shadowBlur, cgShadowColor);
-
- CGContextBeginTransparencyLayer(c, NULL);
- CGContextScaleCTM(c, 1.0, -1.0);
- CGContextClipToMask(c, CGRectMake(itemImagePosition.x, -itemImagePosition.y, itemImageSize.width, -itemImageSize.height), [itemImage CGImage]);
-
- 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);
-
-
- 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];
阅读(1028) | 评论(0) | 转发(0) |