UIView 反转遮罩 MaskView
UIView invert mask MaskView
我想对我的 UIView 应用倒置遮罩。我将遮罩设置为带有透明图像的 UIImageView。但是
的输出
view.mask = imageView
不是想要的结果。我怎样才能达到如下所示的预期结果?所需的结果使用遮罩切口作为透明度。当我检查视图的遮罩时,它不是 CAShapeLayer,所以我不能那样反转它。
看来你可以做一些事情。您可以使用您拥有的图像,但遮盖一个白色视图并在其后面放置一个蓝色视图。或者您可以通过反转透明度来调整您正在使用的图像资产。或者您可以使用 CoreImage
在代码中执行此操作。例如:
func invertMask(_ image: UIImage) -> UIImage?
{
guard let inputMaskImage = CIImage(image: image),
let backgroundImageFilter = CIFilter(name: "CIConstantColorGenerator", withInputParameters: [kCIInputColorKey: CIColor.black]),
let inputColorFilter = CIFilter(name: "CIConstantColorGenerator", withInputParameters: [kCIInputColorKey: CIColor.clear]),
let inputImage = inputColorFilter.outputImage,
let backgroundImage = backgroundImageFilter.outputImage,
let filter = CIFilter(name: "CIBlendWithAlphaMask", withInputParameters: [kCIInputImageKey: inputImage, kCIInputBackgroundImageKey: backgroundImage, kCIInputMaskImageKey: inputMaskImage]),
let filterOutput = filter.outputImage,
let outputImage = CIContext().createCGImage(filterOutput, from: inputMaskImage.extent) else { return nil }
let finalOutputImage = UIImage(cgImage: outputImage)
return finalOutputImage
}
我想对我的 UIView 应用倒置遮罩。我将遮罩设置为带有透明图像的 UIImageView。但是
的输出view.mask = imageView
不是想要的结果。我怎样才能达到如下所示的预期结果?所需的结果使用遮罩切口作为透明度。当我检查视图的遮罩时,它不是 CAShapeLayer,所以我不能那样反转它。
看来你可以做一些事情。您可以使用您拥有的图像,但遮盖一个白色视图并在其后面放置一个蓝色视图。或者您可以通过反转透明度来调整您正在使用的图像资产。或者您可以使用 CoreImage
在代码中执行此操作。例如:
func invertMask(_ image: UIImage) -> UIImage?
{
guard let inputMaskImage = CIImage(image: image),
let backgroundImageFilter = CIFilter(name: "CIConstantColorGenerator", withInputParameters: [kCIInputColorKey: CIColor.black]),
let inputColorFilter = CIFilter(name: "CIConstantColorGenerator", withInputParameters: [kCIInputColorKey: CIColor.clear]),
let inputImage = inputColorFilter.outputImage,
let backgroundImage = backgroundImageFilter.outputImage,
let filter = CIFilter(name: "CIBlendWithAlphaMask", withInputParameters: [kCIInputImageKey: inputImage, kCIInputBackgroundImageKey: backgroundImage, kCIInputMaskImageKey: inputMaskImage]),
let filterOutput = filter.outputImage,
let outputImage = CIContext().createCGImage(filterOutput, from: inputMaskImage.extent) else { return nil }
let finalOutputImage = UIImage(cgImage: outputImage)
return finalOutputImage
}