swift - 在 UIImageView 之上的 Swift 上将蒙版层作为 UIImage

标签 swift image image-processing uiimageview uiimage

我正在尝试获取应用于 UIImageView 的 mask 的 UIImage

我正在使用 UIBezierPath 添加 mask ,并希望将实际 mask 层作为 UIImage,而不是整个图像。将其视为裁剪功能。

我正在使用以下方式裁剪图像:

func cropImage() {
    shapeLayer.fillColor = UIColor.black.cgColor
    viewSource.imageView.layer.mask = shapeLayer
    viewSource.imageView.layer.masksToBounds = true

    UIGraphicsBeginImageContextWithOptions(viewSource.imageView.bounds.size, false, 1)
    viewSource.imageView.layer.render(in: UIGraphicsGetCurrentContext()!)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    self.completionObservable.onNext(newImage)
}

这最终为我提供了旧尺寸(初始 imageView 宽度和高度)之上的蒙版图像。但我只想拥有蒙版图像,不包括它们周围的白色背景。

界面如图:

enter image description here

enter image description here

最佳答案

我现在明白你的意思了。答案在这里,只需更新 imageContext 的大小即可。

          UIGraphicsBeginImageContextWithOptions((shapeLayer.path?.boundingBoxOfPath)!.size, false, 1)

如果不是那么简单,可以试试CIImage管道来实现。

    let context =  CIContext()
    let m1 = newImage?.cgImage
    let m = CIImage.init(cgImage: m1!)
    let bounds = imageView.layer.bounds
    let cgImage =   context.createCGImage(m, from: CGRect.init(x: 0, y: bounds.size.height, width: bounds.size.width, height: bounds.size.height))
    let newUIImage = UIImage.init(cgImage: cgImage!)

您可能需要调整变换。

关于swift - 在 UIImageView 之上的 Swift 上将蒙版层作为 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54316574/

相关文章:

json - Swift 从 Dictionary of Dictionary 中删除 optional

ios - swift : equivalent to respondToSelector

c# - 运行时不显示图像 C# WPF

python - 簇/ Blob 检测

ios - swift中的负数模

ios - 快速单击按钮时出错

image - CSS3 旋转动画

html - 保持 div 和图像分离实体

algorithm - 线组之间的距离

image-processing - 从通过混合一堆图像创建的视频中提取帧正在改变帧的完整性