I want to "lighten" a certain color by applying an alpha of 0.3 to it. This is shown on a white background.
I would like to determine the opaque color which corresponds to this semi transparent color shown on a white background. The reason is that I use this as view controllers's background color, and when this background is semitransparent the transitions look bad.
I have not tried anything because have no idea about a reasonable way to approach this except maybe taking a snapshot and get the color of it but this seems a bit of an overkill. Can't find any infos, search results are cluttered with "how to make a background semitransparent" etc
Edit: Putting together imataptool's answer parts (and porting to Swift), this is what I came up with:
extension UIColor {
static func opaqueColorByDisplayingTransparentColorOnBackground(transparentColor: UIColor, backgroundColor: UIColor) -> UIColor {
let bgView = UIView(frame: CGRectMake(0, 0, 1, 1))
bgView.backgroundColor = backgroundColor
let overlayView = UIView(frame: CGRectMake(0, 0, 1, 1))
overlayView.backgroundColor = transparentColor
bgView.addSubview(overlayView)
let image = UIView.imageWithView(bgView)
let provider = CGImageGetDataProvider(image.CGImage)
let pixelData = CGDataProviderCopyData(provider)
let data = CFDataGetBytePtr(pixelData)
return UIColor(
red: CGFloat(data[0]) / 255.0,
green: CGFloat(data[1]) / 255.0,
blue: CGFloat(data[2]) / 255.0,
alpha: 1
)
}
}
extension UIView {
// src http://stackoverflow.com/a/32042439/930450
class func imageWithView(view: UIView) -> UIImage {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0)
view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
}