如何在普通的UIView(不是UIImage)上获得乘法混合模式 [英] How to get multiply blend mode on a plain UIView (not UIImage)
问题描述
我的iPad应用程序中有一个图像,我基本上想在其顶部放置一个滤色器.为此,我有一个彩色的UIView,它被遮罩为覆盖图像的特定形状.由于调整Alpha并不能达到我想要的效果,因此我想使用混合模式.
I have an image in my iPad app and I basically want to place a color filter on top of it. For this I have a colored UIView that is masked to a certain shape that I put over the image. Since adjusting the alpha isn't giving me the desired effect I'd like to use blend modes instead.
据我所知,您只能在图像上使用混合模式,而不能在普通视图上使用.视图的颜色是动态的,所以我不能只使用图片.
As far as I know you can only use blend modes on images and not plain views. The color of the view is dynamic so I can't just use a picture instead.
我还尝试将视图栅格化为图像,但是像素和奇数之类的东西都出现了,但是也许我做错了.
I also tried rasterizing the view to an image, but that got all pixely and odd or something, but maybe I did something wrong.
因此,基本问题是:是否可以将混合模式应用于视图?还是应该采用完全不同的方法来达到相同的目标?
So, the basic question is: Is it possible to apply blend modes to views? Or should I take a completely different approach to reach the same goal?
推荐答案
看看CALayer的compositingFilter的文档:
Take a look at the docs for CALayer's compositingFilter: https://developer.apple.com/documentation/quartzcore/calayer/1410748-compositingfilter
在颜色叠加视图上,您可以将view.layer.compositingFilter
设置为替换为您自己的图像进行测试)
On your color overlay view you can set view.layer.compositingFilter
to a CICategoryCompositeOperation to achieve blending with the content behind it. Here is some sample playground code with a multiply blend mode applied to test it out (replace the UIImage(named: "")
with your own image for testing)
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let mainView = UIView()
self.view = mainView
let image = UIImageView()
image.translatesAutoresizingMaskIntoConstraints = false;
image.image = UIImage(named: "maxresdefault.jpg")
mainView.addSubview(image)
let overlay = UIView()
overlay.translatesAutoresizingMaskIntoConstraints = false;
overlay.backgroundColor = .red
overlay.layer.compositingFilter = "multiplyBlendMode"
mainView.addSubview(overlay)
mainView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[subview]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: ["subview": view]))
mainView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[subview]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: ["subview": view]))
mainView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[subview]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: ["subview": overlay]))
mainView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[subview]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: ["subview": overlay]))
}
}
PlaygroundPage.current.liveView = MyViewController()
这篇关于如何在普通的UIView(不是UIImage)上获得乘法混合模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!