用颜色覆盖 UIImage?
我试图在一些当前的 UIImage(白色)上添加黑色叠加层。 我一直在尝试使用以下代码:
[[UIColor blackColor] set];
[image drawAtPoint:CGPointMake(0, 0) blendMode:kCGBlendModeOverlay alpha:1.0];
但它不起作用,而且我很确定 set 不应该在那里。
I'm attempting to add a black overlay over some current UIImage's (which are white). I've been trying to use following code:
[[UIColor blackColor] set];
[image drawAtPoint:CGPointMake(0, 0) blendMode:kCGBlendModeOverlay alpha:1.0];
But it's not working, and I'm pretty sure set isn't supposed to be there.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
因此,将所有答案总结为一个,这是一种从
iOS 6
一直到iOS 11
以及各种图像和图标都能完美运行的直接方法:更新: Swift 3 版本
So, to sum up all the answers into one here's the drop-in method that works perfectly from
iOS 6
all the way up toiOS 11
with all kinds of images and icons:Update: Swift 3 version
您需要将上下文剪切到图像蒙版,然后用纯色填充:
注意:
myImage
应该是包含UIImage
的实例变量。 我不确定它是否从 alpha 通道或强度中获取蒙版,所以两者都尝试一下。You will want to clip the context to an image mask and then fill with a solid color:
Note:
myImage
should be an instance variable that contains anUIImage
. I'm not sure whether it takes the mask from the alpha channel or the intensity so try both.我刚刚写了一个教程来帮助解决这个问题。 我的方法为您提供了 UIImage 的副本,其中包含您想要的颜色更改。 rpetrich 的方法很棒,但要求您创建一个子类。 我的方法只是几行代码,可以将其放在您需要的任何地方。 http://coffeeshopped.com/2010/09/ iphone-如何动态为用户界面图像上色
I just wrote a tutorial that will help with this. My approach gives you a copy of a UIImage, with the color alterations that you want. rpetrich's approach is great, but requires that you're creating a subclass. My approach is just a few lines of code that can be dropped in wherever you need them. http://coffeeshopped.com/2010/09/iphone-how-to-dynamically-color-a-uiimage
看看这个方法
Look on this method
从 iOS 7 开始,有一个更简单的解决方案:
Since iOS 7 there is a much simpler solution:
除了 rpetrich 的解决方案(顺便说一下,这很好 - 帮助我),您还可以将 CGContextClipToMask 行替换为:
它是 SourceIn 混合模式,它负责通过 GetCurrentContext 中的任何内容来掩盖颜色。
In addition to the solution by rpetrich (which is great by the way - help me superbly), you can also replace the CGContextClipToMask line with:
It's the SourceIn blendmode that does the job of masking the color by whatever is in the GetCurrentContext.
以下是如何使用 Swift 3.0 并使用 UIImage 扩展来实现此目的。 超级简单。
然后运行它只需执行以下操作:
Here's how you do it with Swift 3.0 and using extensions to UIImage. Super simple.
Then to run it simply do:
您可以通过以下方式在 Swift 4.x 中以编程方式执行此操作:
You can do that programmatically in Swift 4.x on the next way:
-set
用于设置后续绘图操作的颜色,不包括位图传输。 我建议第一次调用时,在UIImageView
上显示另一个(空)UIView
并设置其背景颜色:显然,您应该使用所需的白色和 alpha 值。
-set
is used to set the colour of subsequent drawing operations which doesn't include blits. I suggest as a first call, displaying another (empty)UIView
over yourUIImageView
and setting its background colour:Obviously you should use the white and alpha values you want.