我试图在一些当前的UIImage(白色的)上添加一个黑色的覆盖。我一直在尝试使用以下代码:
[[UIColor blackColor] set];
[image drawAtPoint:CGPointMake(0, 0) blendMode:kCGBlendModeOverlay alpha:1.0];
但它不起作用,我很确定set不应该在那里。
发布于 2009-05-11 03:37:34
您将希望剪裁图像蒙版的上下文,然后使用纯色进行填充:
- (void)drawRect:(CGRect)rect
{
CGRect bounds = [self bounds];
[[UIColor blackColor] set];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClipToMask(context, bounds, [myImage CGImage]);
CGContextFillRect(context, bounds);
}
注意:myImage
应该是一个包含UIImage
的实例变量。我不确定它是从alpha通道中提取遮罩,还是从强度中提取,所以两个都试一下。
发布于 2010-09-28 01:40:29
我刚刚写了一篇教程,将对此有所帮助。我的方法为您提供了一个UIImage副本,其中包含您想要的颜色更改。rpetrich的方法很好,但要求您创建一个子类。我的方法是只需要几行代码,就可以将它们放在您需要的任何地方。http://coffeeshopped.com/2010/09/iphone-how-to-dynamically-color-a-uiimage
NSString *name = @"badge.png";
UIImage *img = [UIImage imageNamed:name];
// begin a new image context, to draw our colored image onto
UIGraphicsBeginImageContext(img.size);
// get a reference to that context we created
CGContextRef context = UIGraphicsGetCurrentContext();
// set the fill color
[color setFill];
// translate/flip the graphics context (for transforming from CG* coords to UI* coords
CGContextTranslateCTM(context, 0, img.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
// set the blend mode to color burn, and the original image
CGContextSetBlendMode(context, kCGBlendModeColorBurn);
CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);
CGContextDrawImage(context, rect, img.CGImage);
// set a mask that matches the shape of the image, then draw (color burn) a colored rectangle
CGContextClipToMask(context, rect, img.CGImage);
CGContextAddRect(context, rect);
CGContextDrawPath(context,kCGPathFill);
// generate a new UIImage from the graphics context we drew onto
UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//return the color-burned image
return coloredImg;
发布于 2012-05-16 21:57:07
看看这个方法
+ (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size;
{
UIImage *img = nil;
CGRect rect = CGRectMake(0, 0, size.width, size.height);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context,
color.CGColor);
CGContextFillRect(context, rect);
img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
https://stackoverflow.com/questions/845278
复制相似问题