Search code examples
iosuiimageviewuiimage

Change UIImage render mode at runtime


In an app I am working on I have some UIImageViews that may (or may not) need to be customised. How can I change the rendering mode of an image that was loaded as original to template at runtime?


Solution

  • You can init a UIImage from another cgImage, then you can render it as you need

    ExampleCode

    let originalImage = UIImage(named: "TimeClock2Filled")?.withRenderingMode(.alwaysOriginal)
    if let original = originalImage?.cgImage {
        let image2 = UIImage(cgImage: original).withRenderingMode(.alwaysTemplate)
    }
    

    Example code Objective-C

    UIImage * image = [[UIImage imageNamed:@"TimeClock2Filled"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    if(image.CGImage != nil) {
        UIImage * image2 = [[UIImage imageWithCGImage:image.CGImage]imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    }
    

    this works just fine was tested