我有一個圖片,點擊一個按鈕後,它的alpha會隨着它的黑暗而變化。如何設置圓形圖像的背景顏色?
我想過這樣做的最好辦法是以下幾點:
cell.followUserImage.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.5)
這裏是改變之前的圖像:
這裏有這個圖像之後:
你可以看到,它只是使角落變暗。我希望它只是變暗圖像並改變它的alpha分量。
我該怎麼做呢?從@Rob
這裏
我有一個圖片,點擊一個按鈕後,它的alpha會隨着它的黑暗而變化。如何設置圓形圖像的背景顏色?
我想過這樣做的最好辦法是以下幾點:
cell.followUserImage.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.5)
這裏是改變之前的圖像:
這裏有這個圖像之後:
你可以看到,它只是使角落變暗。我希望它只是變暗圖像並改變它的alpha分量。
我該怎麼做呢?從@Rob
這裏
偉大的想法是在代碼斯威夫特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)
使整個imageView
半透明你可以設置它的阿爾法:
imageView.alpha = 0.5
如果你想創建一個黑暗的形象,掩蓋於原始圖像,你可以做以下(斯威夫特3):
imageView.image = image.darkened()
凡
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
}
}
或者,斯威夫特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
}
}
即產率(示出圖像旁邊變暗再現):
「並更改它的alpha分量」是指顏色疊加層或圖像本身的alpha分量?角落應該保持透明,對嗎? – alexburtnik
圖像本身。並且角落應該保持透明 –
您希望淺灰色和綠色都變暗,但不是透明部分? – Rob