How can I color a UIImage in Swift?

后端 未结 20 2262
执念已碎
执念已碎 2020-11-29 18:27

I have an image called arrowWhite. I want to colour this image to black.

func attachDropDownArrow() -> NSMutableAttributedString {
    let im         


        
20条回答
  •  悲&欢浪女
    2020-11-29 18:55

    Swift 3 version with scale and Orientation from @kuzdu answer

    extension UIImage {
    
        func mask(_ color: UIColor) -> UIImage? {
            let maskImage = cgImage!
    
            let width = (cgImage?.width)!
            let height = (cgImage?.height)!
            let bounds = CGRect(x: 0, y: 0, width: width, height: height)
    
            let colorSpace = CGColorSpaceCreateDeviceRGB()
            let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
            let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)!
    
            context.clip(to: bounds, mask: maskImage)
            context.setFillColor(color.cgColor)
            context.fill(bounds)
    
            if let cgImage = context.makeImage() {
                let coloredImage = UIImage.init(cgImage: cgImage, scale: scale, orientation: imageOrientation)
                return coloredImage
            } else {
                return nil
            }
        }
    }
    

提交回复
热议问题