1. 程式人生 > >swift 改變圖片顏色

swift 改變圖片顏色

1、擴充套件Image

extension UIImage {                                                                 
    func imageWithColor(tintColor: UIColor) -> UIImage {                            
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)        
                                                                                    
        let context = UIGraphicsGetCurrentContext() as CGContextRef                 
        CGContextTranslateCTM(context, 0, self.size.height)                         
        CGContextScaleCTM(context, 1.0, -1.0);                                      
        CGContextSetBlendMode(context, kCGBlendModeNormal)                          
                                                                                    
        let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect    
        CGContextClipToMask(context, rect, self.CGImage)                            
        tintColor.setFill()                                                         
        CGContextFillRect(context, rect)                                            
                                                                                    
        let newImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage       
        UIGraphicsEndImageContext()                                                 
                                                                                    
        return newImage                                                             
    }                                                                               
}  

2、使用
clockImage.image = clockImage.image!.imageWithColor(color).imageWithRenderingMode(.AlwaysOriginal)