ios - 如何在路径中制作透明区域uiimage

标签 ios swift core-graphics

在 iOS 中,
我有一张图片。
然后,我想在图像的特定路径中制作透明区域。
下图是一些图像。并且,心脏区域是随机路径成为透明区域。
我只有一张完整图片。
我想使图像的特定区域透明。它是 UIImage,而不是 UIImageView。所以,我不能使用 mask 。

https://stackoverflow.com/a/8306254/2160799
我尝试使用此解决方案,但心形区域充满了蓝色,不透明。 :(
文档是这样解释的。因为解决方案使用 imageContext(不是窗口或位图上下文),所以我不应该使用函数 (CGContext.clear(_:))

If the provided context is a window or bitmap context, Core Graphics clears the rectangle. For other context types, Core Graphics fills the rectangle in a device-dependent manner. However, you should not use this function in contexts other than window or bitmap contexts.

enter image description here

最佳答案

您可以使用以下代码段。在这里,您将使用 API UIGraphicsBeginImageContextWithOptions(_:_:_:) 创建图像上下文,并将不透明参数指定为 false,这将使最终图像透明。

UIGraphicsBeginImageContextWithOptions(image.size, false, 0)
image.draw(at: .zero)
if let context = UIGraphicsGetCurrentContext() {
    context.addPath(bezierPath.cgPath)
    context.setBlendMode(.clear)
    context.setFillColor(UIColor.clear.cgColor)
    context.fillPath()

    let capturedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
}

关于ios - 如何在路径中制作透明区域uiimage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58830233/

相关文章:

ios - CGRect 和 CGPath 的交集

swift - 从Swift 3.x转换为5

swift - 如何使用 RxCocoa 将图像设置为 UIButton

ios - 将背景图像添加到 SpriteKit 项目

ios - 其中 key :matchesQuery: is not giving any result

ios - 此 iPhone 6s Plus 运行的是 iOS 12.2 (16E5212f),此版本的 Xcode 可能不支持

iphone - UITableView 的单个 View 中存在多少个单元格?

swift - 如何更改CAShapeLayer内的区域?

ios - 在第 4 代 iPad 上缩放图像很慢,是否有更快的替代方案?

objective-c - 将任意形状的 CGPath 动画化为矩形