Changing UIImage color

前端 未结 13 1480
我寻月下人不归
我寻月下人不归 2020-11-28 19:28

I\'m trying to change color of UIImage. My code:

-(UIImage *)coloredImage:(UIImage *)firstImage withColor:(UIColor *)color {
    UIGraphicsBeginImageContext(         


        
13条回答
  •  半阙折子戏
    2020-11-28 19:59

    Swift 4.2 Solution

    extension UIImage {
        func withColor(_ color: UIColor) -> UIImage {
            UIGraphicsBeginImageContextWithOptions(size, false, scale)
            guard let ctx = UIGraphicsGetCurrentContext(), let cgImage = cgImage else { return self }
            color.setFill()
            ctx.translateBy(x: 0, y: size.height)
            ctx.scaleBy(x: 1.0, y: -1.0)
            ctx.clip(to: CGRect(x: 0, y: 0, width: size.width, height: size.height), mask: cgImage)
            ctx.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
            guard let colored = UIGraphicsGetImageFromCurrentImageContext() else { return self }
            UIGraphicsEndImageContext()
            return colored
        }
    }
    
    // Usage:
    // let redImage = UIImage().withColor(.red)
    

提交回复
热议问题