Search code examples
imagecanvasswiftuidrawing

SwiftUI - Unable to change color of asset image drawn in canvas


I'm trying to change the foreground color of an image drawn using the SwiftUI canvas. It's working with an image from SFSymbols but not working for a custom image in assets. The image is in format SVG set with "template mode rendering" in assets. The image is drawn, but stay white.

// create canvas to draw
        Canvas { context, size in

                var image = context.resolve(Image("season-drinkfrom")) => not working
                //var image = context.resolve(Image(systemName: "star.fill")) => working
                image.shading = .color(.green)
                
                let imageRect = CGRect(x: drinkFromOriginX - imageSize/2, y: 0, width: imageSize, height: imageSize)
                context.draw(image, in: imageRect)
            }           
            
        }

Asset image keeps white foreground color - not working:

SFSymbol image uses new color (green) - working:

enter image description here

It's probably a context error for the image.

For info, the asset image set in Assets catalog:

enter image description here


Solution

  • This is the code and the image I used to test changing the color of a SVG format image.

    The image is "SVG_Logo", downloaded from: https://en.wikipedia.org/wiki/SVG#/media/File:SVG_Logo.svg

    and dragged into the Assets.xcassets of the Xcode project.

    Note, I un-ticked the Resizing Preserve Vector Data and the image turns green, otherwise the image stays the same.

    struct ContentView: View {
        var body: some View {
            Canvas { context, size in
                var image = context.resolve(Image("SVG_Logo"))
                // var image = context.resolve(Image(systemName: "star.fill"))
                image.shading = .color(.green)
                let imageRect = CGRect(x: 0, y: 0, width: 222, height: 222)
                context.draw(image, in: imageRect)
            }
        }
    }