首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >用颜色覆盖UIImage?

用颜色覆盖UIImage?
EN

Stack Overflow用户
提问于 2009-05-10 12:52:42
回答 6查看 50.4K关注 0票数 17

我试图在一些当前的UIImage(白色的)上添加一个黑色的覆盖。我一直在尝试使用以下代码:

代码语言:javascript
复制
[[UIColor blackColor] set];
[image drawAtPoint:CGPointMake(0, 0) blendMode:kCGBlendModeOverlay alpha:1.0];

但它不起作用,我很确定set不应该在那里。

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2009-05-11 03:37:34

您将希望剪裁图像蒙版的上下文,然后使用纯色进行填充:

代码语言:javascript
复制
- (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通道中提取遮罩,还是从强度中提取,所以两个都试一下。

票数 31
EN

Stack Overflow用户

发布于 2010-09-28 01:40:29

我刚刚写了一篇教程,将对此有所帮助。我的方法为您提供了一个UIImage副本,其中包含您想要的颜色更改。rpetrich的方法很好,但要求您创建一个子类。我的方法是只需要几行代码,就可以将它们放在您需要的任何地方。http://coffeeshopped.com/2010/09/iphone-how-to-dynamically-color-a-uiimage

代码语言:javascript
复制
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;
票数 11
EN

Stack Overflow用户

发布于 2012-05-16 21:57:07

看看这个方法

代码语言:javascript
复制
 + (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;
    }
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/845278

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档