How to get multiply blend mode on a plain UIView (not UIImage)

后端 未结 2 1094
刺人心
刺人心 2021-02-04 01:47

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

2条回答
  •  有刺的猬
    2021-02-04 02:25

    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()
    

提交回复
热议问题