How can I color a UIImage in Swift?

后端 未结 20 2275
执念已碎
执念已碎 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 19:15

    Since I found Darko's answer very helpful in colorizing custom pins for mapView annotations, but had to do some conversions for Swift 3, thought I'd share the updated code along with my recommendation for his answer:

    extension UIImage {
        func maskWithColor(color: UIColor) -> UIImage {
    
            var maskImage = self.CGImage
            let width = self.size.width
            let height = self.size.height
            let bounds = CGRect(x: 0, y: 0, width: width, height: height)
    
            let colorSpace = CGColorSpaceCreateDeviceRGB()
            let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
            let bitmapContext = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)
    
            bitmapContext!.clip(to: bounds, mask: maskImage!)
            bitmapContext!.setFillColor(color.cgColor)
            bitmapContext!.fill(bounds)
    
            let cImage = bitmapContext!.makeImage()
            let coloredImage = UIImage(CGImage: cImage)
    
            return coloredImage!
        }
    }
    

提交回复
热议问题