问题
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?
回答1:
Take a look at the docs for CALayer's compositingFilter: https://developer.apple.com/documentation/quartzcore/calayer/1410748-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()
来源:https://stackoverflow.com/questions/16407396/how-to-get-multiply-blend-mode-on-a-plain-uiview-not-uiimage