iOS: create an darker version of UIImage and leave transparent pixels unchanged?

前端 未结 4 488
小蘑菇
小蘑菇 2021-02-05 16:31

I found

Create new UIImage by adding shadow to existing UIImage

and

UIImage, is there an easy way to make it darker or all black

But the selected

4条回答
  •  名媛妹妹
    2021-02-05 17:22

    Here's David's answer in Swift 5:

    class func colorizeImage(_ image: UIImage?, with color: UIColor?) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(image?.size ?? CGSize.zero, _: false, _: image?.scale ?? 0.0)
    
        let context = UIGraphicsGetCurrentContext()
        let area = CGRect(x: 0, y: 0, width: image?.size.width ?? 0.0, height: image?.size.height ?? 0.0)
    
        context?.scaleBy(x: 1, y: -1)
        context?.translateBy(x: 0, y: -area.size.height)
    
        context?.saveGState()
        context?.clip(to: area, mask: (image?.cgImage)!)
    
        color?.set()
        context?.fill(area)
    
        context?.restoreGState()
    
        if let context = context {
            context.setBlendMode(.multiply)
        }
    
        context!.draw((image?.cgImage)!, in: area)
    
        let colorizedImage = UIGraphicsGetImageFromCurrentImageContext()
    
        UIGraphicsEndImageContext()
    
        return colorizedImage
    }
    

提交回复
热议问题