在 iOS 开发中,要在 UIImage 上制作一种透明的颜色,可以使用以下步骤:
import UIKit
extension UIImage {
func imageWithTransparentColor(opacity: CGFloat) -> UIImage? {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, scale)
let context = UIGraphicsGetCurrentContext()
context?.setBlendMode(.multiply)
let transparentColor = UIColor(white: 0, alpha: opacity)
context?.setFillColor(transparentColor.cgColor)
context?.fill(rect)
draw(in: rect, blendMode: .multiply, alpha: 1)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
let image = UIImage(named: "myImage.png")
let transparentImage = image?.imageWithTransparentColor(opacity: 0.5)
这样,就可以在 UIImage 上制作一种透明的颜色了。
领取专属 10元无门槛券
手把手带您无忧上云