如何设置 UIImage 的不透明度/alpha?
我知道你可以用 UIImageView 做到这一点,但是可以对 UIImage 做到这一点吗?我想让 UIImageView 的动画图像数组属性成为相同图像但具有不同不透明度的数组。想法?
I know you can do this with a UIImageView, but can it be done to a UIImage? I want to have the animation images array property of a UIImageView to be an array of the same image but with different opacities. Thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
我只需要这样做,但认为史蒂文的解决方案会很慢。这应该使用图形硬件。在 UIImage 上创建一个类别:
I just needed to do this, but thought Steven's solution would be slow. This should hopefully use graphics HW. Create a category on UIImage:
设置其显示视图的不透明度。
在动画中使用它。您可以在一段时间内更改动画中的 Alpha。
Set the opacity of its view it is showed in.
Use this in an animation. You can change the alpha in an animation for an duration.
基于 Alexey Ishkov 的回答,但在 Swift 中
我使用了 UIImage 类的扩展。
Swift 2:
UIImage 扩展:
要使用:
Swift 3/4/5:
请注意,此实现返回一个可选的 UIImage。这是因为在 Swift 3 中,
UIGraphicsGetImageFromCurrentImageContext
现在返回一个可选值。如果上下文为零或不是使用UIGraphicsBeginImageContext
创建的,则该值可能为零。UIImage 扩展:
使用方法:
Based on Alexey Ishkov's answer, but in Swift
I used an extension of the UIImage class.
Swift 2:
UIImage Extension:
To use:
Swift 3/4/5:
Note that this implementation returns an optional UIImage. This is because in Swift 3
UIGraphicsGetImageFromCurrentImageContext
now returns an optional. This value could be nil if the context is nil or what not created withUIGraphicsBeginImageContext
.UIImage Extension:
To use:
有更简单的解决方案:
there is much easier solution:
嘿嘿,感谢 Xamarin 用户! :) 这里它被翻译成 c#
用法示例:
Hey hey thanks from Xamarin user! :) Here it goes translated to c#
Usage example:
我意识到这已经很晚了,但我需要这样的东西,所以我想出了一个快速而肮脏的方法来做到这一点。
I realize this is quite late, but I needed something like this so I whipped up a quick and dirty method to do this.
与其他人相同的结果,不同的风格:
same result as others, different style:
斯威夫特5:
Swift 5:
如果您正在尝试金属渲染和如果您在第一个回复中提取由 imageByApplyingAlpha 生成的 CGImage,您最终可能会得到比您预期更大的 Metal 渲染。在尝试 Metal 时,您可能需要更改 imageByApplyingAlpha 中的一行代码:
如果您使用比例因子为 3.0 的设备(例如 iPhone 11 Pro Max),则上面显示的 0.0 比例因子将为您提供一个 CGImage比您预期的大三倍。将比例因子更改为 1.0 应避免任何缩放。
希望这个答复能为初学者省去很多麻烦。
If you're experimenting with Metal rendering & you're extracting the CGImage generated by imageByApplyingAlpha in the first reply, you may end up with a Metal rendering that's larger than you expect. While experimenting with Metal, you may want to change one line of code in imageByApplyingAlpha:
If you're using a device with a scale factor of 3.0, like the iPhone 11 Pro Max, the 0.0 scale factor shown above will give you an CGImage that's three times larger than you're expecting. Changing the scale factor to 1.0 should avoid any scaling.
Hopefully, this reply will save beginners a lot of aggravation.