Khushbu Desai
Khushbu Desai

Reputation: 1023

Masked image's Background color

I have used following code for masking

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

Now, I want to change background color to yellow, like this:

example

How can I achieve this?

Upvotes: 1

Views: 374

Answers (2)

harshal jadhav
harshal jadhav

Reputation: 5684

Heres a small code snippet with background color change

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
    }      
}

Upvotes: 1

Abdelahad Darwish
Abdelahad Darwish

Reputation: 6067

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

Upvotes: 1

Related Questions