Alexandre Lara
Alexandre Lara

Reputation: 2568

How to put a black color with opacity on an image in Swift 3

I'd like to know how can I put a black rectangle with opacity on the top of an image in Swift 3. For example:

enter image description here enter image description here

Upvotes: 3

Views: 3843

Answers (2)

Anton Rogachevskyi
Anton Rogachevskyi

Reputation: 219

func drawRectOn(image: UIImage) -> UIImage {
    UIGraphicsBeginImageContext(image.size)
    image.draw(at: CGPoint.zero)
    let context = UIGraphicsGetCurrentContext()

    // set fill gray and alpha
    context!.setFillColor(gray: 0, alpha: 0.5)
    context!.move(to: CGPoint(x: 0, y: 0))
    context!.fill(CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
    context!.strokePath()
    let resultImage = UIGraphicsGetImageFromCurrentImageContext()

    // end the graphics context
    UIGraphicsEndImageContext()

    return resultImage!

}

Upvotes: 2

Kenny Gunderman
Kenny Gunderman

Reputation: 500

you can create a UIView that is black with an opacity and make it the same size of your UIImageView and add it as subview. Try something like:

let tintView = UIView()
tintView.backgroundColor = UIColor(white: 0, alpha: 0.5) //change to your liking
tintView.frame = CGRect(x: 0, y: 0, width: imageView.frame.width, height: imageView.frame.height)

imageView.addSubview(tintView)

imageView = Your UIImageView

Upvotes: 6

Related Questions