做一个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;
CGColorRefcgColor = [bgColor CGColor];
CGColorRefcgShadowColor = [shadowColor CGColor];
CGFloatcomponents[16] ={1,1,1,alpha1,1,1,1,alpha1,1,1,1,alpha2,1,1,1,alpha3};
CGFloatlocations[4] = {0,0.5,0.6,1};
CGColorSpaceRef colorSpace =CGColorSpaceCreateDevice
RGB();
CGGradientRef colorGradient =CGGradientCreateWithColo
rComponents(colorSpace, components,locations, (size_t)4);
CGRectcontextRect;
contextRect.origin.x = 0.0f;
contextRect.origin.y = 0.0f;
contextRect.size = [image size];
//contextRect.size = CGSizeMake([image size].width+5,[imagesize].height+5);
// Retrievesource image and begin image context
UIImage*itemImage = image;
CGSizeitemImageSize = [itemImage size];
CGPointitemImagePosition;
itemImagePosition.x = ceilf((contextRect.size.width -itemImageSize.width) / 2);
itemImagePosition.y = ceilf((contextRect.size.height -itemImageSize.height) / 2);
UIGraphicsBeginImageCont
ext(contextRect.size);
CGContextRefc = UIGraphicsGetCurrentCont
ext();
// Setupshadow
CGContextSetShadowWithCo
lor(c, shadowOffset, shadowBlur,cgShadowColor);
// Setuptransparency layer and clip to mask
CGContextBeginTransparen
cyLayer(c, NULL);
CGContextScaleCTM(c, 1.0, -1.0);
CGContextClipToMask(c, CGRectMake(itemImagePosition.x,-itemImagePosition.y, itemImageSize.width, -itemImageSize.height),[itemImage CGImage]);
// Fill andend the transparency layer
CGContextSetFillColorWit
hColor(c,cgColor);
contextRect.size.height = -contextRect.size.height;
CGContextFillRect(c, contextRect);
CGContextDrawLinearGradi
ent(c,colorGradient,CGPointZero,CGPointMake(contextRect.size.width*1.0/4.0,contextRect.size.height),0);
CGContextEndTransparency
Layer(c);
//CGPointMake(contextRect.size.width*3.0/4.0, 0)
// Setselected image and end context
UIImage*resultImage = UIGraphicsGetImageFromCu
rrentImageContext();
UIGraphicsEndImageContex
t();
CGColorSpaceRelease(colorSpace);
CGGradientRelease(colorGradient);
returnresultImage;
}
用法如下
UIImage *niceImage = [[UIImage imageNamed:@"image_name"]imageWithBackgroundColor :[UIColor colorWithRed:41.0/255.0green: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)
- (UIImage *) imageWithBackgroundColor
}
用法如下
UIImage *niceImage = [[UIImage imageNamed:@"image_name"]imageWithBackgroundColor