Loading SVG smbol in swiftui image

In Swift UI it should be posssible to load a custom symbol from the asset catalog into an image, similar to Image(systemName:) with SF Symbol.


However, with beta3 this does not seem to work for me, or I'm overlooking something…


Image("foo") works fine with bitmaps from the asset catalog, but trying to use Image("bar") with an SVG – which was generated with the SF Symbols app, it delivers just an error log "no image bar was found in main bundle: file"


Any ideas how to make that work?


Thanks


Klaus

Replies

SVG is simply not supported. You need to rasterize (PNG etc) or convert (PDF) it.

PDF also won't load in Image

Well, if SVG is not supported – and I know that traditionally this hasn't been the case –, then why does the SF Symbols app has this export for „Prepare Custom Symbol for XCode“?


See https://developer.apple.com/design/human-interface-guidelines/sf-symbols/overview/ for further details of the proposed process.

It seems that SVG support is new but was half heartedly implemented making it feel as though support is lacking. By my various messings with it so far, raw svg's and custom symbols from SF Symbols are both wonky.

I also ran into this today. I REALLY hope its just a bug, otherwise there's really no point in using custom symbols in SwiftUI.


I did find a work around, but it doesn't really suit my needs - dynamic resizing and tint coloring don't work as they ought to. Here's the workaround:


  var iconName: String

  var dynamicImage: UIImage {
    let configuration = UIImage.SymbolConfiguration(textStyle: .body, scale: .large)
    let image = UIImage(named: iconName) ?? UIImage()
    return image.withConfiguration(configuration)
  }
  
  var body: some View {
    Image(uiImage: dynamicImage)
  }

)
You can do this with SVGKit
Code Block
import SwiftUI
import SVGKit
struct SVGKFastImageViewSUI:UIViewRepresentable
{
  var url:URL
  func makeUIView(context: Context) -> SVGKFastImageView {
    
    //let svg = URL(string: url)!
   // let data = try? Data(contentsOf: url)
    let svgImage = SVGKImage(contentsOf: url)
    return SVGKFastImageView(svgkImage: svgImage ?? SVGKImage())
     
  }
  func updateUIView(_ uiView: SVGKFastImageView, context: Context) {
     
  }
   
   
}
struct SVGImage_Previews: PreviewProvider {
  static var previews: some View {
    SVGKImageViewSUI(url:URL(string:"https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/android.svg")!)
  }
}

  • It does not work. XCode writes me that The body of the Widget entries' view contains the following unsupported types: PlatformViewRepresentableAdapt or<SVGKFastImageViewSUI>

    How did you solve it?

Add a Comment
You can also try this tool: https://github.com/quassummanus/SVG-to-SwiftUI
It so far only supports the SVG path element, but I did have success using it.