简体   繁体   English

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

[英]How to make transparent area uiimage in path

In iOS,在 iOS 中,
I have a image.我有一个图像。
Then, I want to make transparent area in specific path of the image.然后,我想在图像的特定路径中制作透明区域。
The below image is some image.下图是一些图像。 And, the heart area is random path to be transparent area.并且,心脏区域是透明区域的随机路径。
I have just one full image.我只有一张完整的图像。
I want to make transparent specific area of image.我想使图像的特定区域透明。 It is UIImage, not UIImageView.它是 UIImage,而不是 UIImageView。 So, I can't use masking.所以,我不能使用遮罩。

https://stackoverflow.com/a/8306254/2160799 https://stackoverflow.com/a/8306254/2160799
I tried to use this solution, but the heart area was filled with blue color, not transparent.我尝试使用此解决方案,但心脏区域被蓝色填充,不透明。 :( :(
The document explain like this.文档是这样解释的。 Because the solution uses imageContext(not window or bitmap contexts), I should not use the function( CGContext.clear(_:) )因为解决方案使用 imageContext(不是 window 或 bitmap 上下文),所以我不应该使用函数( CGContext.clear(_:)

If the provided context is a window or bitmap context, Core Graphics clears the rectangle.如果提供的上下文是 window 或 bitmap 上下文,Core Graphics 会清除该矩形。 For other context types, Core Graphics fills the rectangle in a device-dependent manner.对于其他上下文类型,Core Graphics 以与设备相关的方式填充矩形。 However, you should not use this function in contexts other than window or bitmap contexts.但是,您不应在 window 或 bitmap 上下文之外的上下文中使用此 function。

在此处输入图像描述

You can use the below snippet.您可以使用以下代码段。 Here you would be creating an imagecontext using the api UIGraphicsBeginImageContextWithOptions(_:_:_:) and specified the opaque parameter as false which would make the end image transparent.在这里,您将使用 api UIGraphicsBeginImageContextWithOptions(_:_:_:)创建一个图像上下文,并将 opaque 参数指定为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()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM