Faisal Syed
Faisal Syed

Reputation: 931

How to set background color of circular image?

I have an image that upon a click of a button, its alpha will change along with its darkness.

The best way I thought about doing this was the following:

cell.followUserImage.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.5)

Here is the image before the change:

enter image description here

Here is the image after:

enter image description here

As you can see, it's only darkening the corners. I would like it to just darken the image and change its alpha component.

How would I go about doing that?

Upvotes: 2

Views: 809

Answers (2)

Rob
Rob

Reputation: 437392

If you want to create a darkened image, masked to that original image, you can do the following (in Swift 3):

imageView.image = image.darkened()

Where

extension UIImage {
    func darkened() -> UIImage? {
        let rect = CGRect(origin: .zero, size: size)
        guard let context = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: Int(size.width) * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Little.rawValue) else { return nil }
        context.draw(cgImage!, in: rect)
        context.clip(to: rect, mask: cgImage!)
        context.setFillColor(UIColor(red: 0, green: 0, blue: 0, alpha: 0.25).cgColor)
        context.fill(rect)
        if let outputCgImage = context.makeImage() {
            return UIImage(cgImage: outputCgImage)
        }
        return nil
    }
}

Or, in Swift 2:

extension UIImage {
    func darkened() -> UIImage? {
        let rect = CGRect(origin: .zero, size: size)
        let context = CGBitmapContextCreate(nil, Int(size.width), Int(size.height), 8, Int(size.width) * 4, CGColorSpaceCreateDeviceRGB(), CGImageAlphaInfo.PremultipliedLast.rawValue | CGBitmapInfo.ByteOrder32Little.rawValue)!

        CGContextDrawImage(context, rect, CGImage!)
        CGContextClipToMask(context, rect, CGImage!)
        CGContextSetFillColorWithColor(context, UIColor(red: 0, green: 0, blue: 0, alpha: 0.25).CGColor)
        CGContextFillRect(context, rect)

        if let outputCgImage = CGBitmapContextCreateImage(context) {
            return UIImage(CGImage: outputCgImage)
        }
        return nil
    }
}

That yields (showing image next to darkened rendition):

enter image description here

Upvotes: 1

alexburtnik
alexburtnik

Reputation: 7741

Great idea from @Rob

Here is the code in Swift 3:

let mask = UIImageView(frame: imageView.bounds)
mask.image = imageView.image
mask.contentMode = imageView.contentMode
imageView.mask = mask

let overlay = UIView(frame: imageView.bounds)
overlay.backgroundColor = UIColor(white: 0, alpha: 0.2)
imageView.addSubview(overlay)

enter image description here

To make the whole imageView semi-transparent you can just set it's alpha:

imageView.alpha = 0.5     

Upvotes: 2

Related Questions