蒙面图像的背景颜色

时间:2017-08-21 10:44:26

标签: ios swift swift3

我使用以下代码进行屏蔽

imgMask = UIImageView(image: image)
imgImage.mask = imgMask

现在,我想将背景颜色更改为黄色,如下所示:

example

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

let templateImage = originalImage.imageWithRenderingMode(UIImageRenderingModeAlwaysTemplate)
myImageView.image = templateImage
myImageView.tintColor = UIColor.orangeColor()

答案 1 :(得分:1)

这是一个带有背景颜色变化的小代码片段

import Foundation
import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var trial: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        let mask = UIImage(named: "mask_image")
        let image = UIImage(named: "wallpaper")

        trial.image = self.maskImage(image: image!, withMask: mask!)
        trial.backgroundColor = UIColor.red
    }
    func maskImage(image: UIImage, withMask maskImage: UIImage) -> UIImage {
        let maskRef = maskImage.cgImage
        let mask = CGImage(
            maskWidth: maskRef!.width,
            height: maskRef!.height,
            bitsPerComponent: maskRef!.bitsPerComponent,
            bitsPerPixel: maskRef!.bitsPerPixel,
            bytesPerRow: maskRef!.bytesPerRow,
            provider: maskRef!.dataProvider!,
            decode: nil,
            shouldInterpolate: false)
        let masked = image.cgImage!.masking(mask!)
        let maskedImage = UIImage(cgImage: masked!)
        // No need to release. Core Foundation objects are automatically memory managed
        return maskedImage
    }      
}