我想为可伸展的UIImage上色,但我不能让它起作用。 在这篇文章的帮助下:How to change the color of an UIImage我已经成功地为我的UIImage着色了但是当我使它变得可伸缩时,颜色没有设置在“新”框架上。
以下是我使用类别设置颜色的方法:
+ (UIImage *)imageNamed:(NSString *)name withColor:(UIColor *)color
{
UIImage *image = [UIImage imageNamed:name];
if (color == nil)
return image;
CGRect rect = CGRectMake(0.f, 0.f, image.size.width, image.size.height);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClipToMask(context, rect, image.CGImage);
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return [UIImage imageWithCGImage:img.CGImage
scale:1.0
orientation:UIImageOrientationDownMirrored];
}
任何建议都表示赞赏......
答案 0 :(得分:1)
此代码应该有效:
+ (UIImage *)imageNamed:(NSString *)name withColor:(UIColor *)theColor
{
UIImage *baseImage = [UIImage imageNamed:name];
UIGraphicsBeginImageContext(baseImage.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect area = CGRectMake(0, 0, baseImage.size.width, baseImage.size.height);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -area.size.height);
CGContextSaveGState(ctx);
CGContextClipToMask(ctx, area, baseImage.CGImage);
[theColor set];
CGContextFillRect(ctx, area);
CGContextRestoreGState(ctx);
CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
CGContextDrawImage(ctx, area, baseImage.CGImage);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
答案 1 :(得分:0)
您的捆绑中有一个图像,并使用上面的颜色对其进行着色,这不会修改原始图像,但会返回一个新图像。此新图像是普通图像,这意味着您看到的颜色是图像中的实际位。如果您现在从新创建的图像而不是原始图像创建新的可伸缩图像,则它应该是正确的颜色。
如果没有创建一个小的演示项目并将其发布在DropBox上,让我们看看它。