Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use .svg images in SwiftUI

Can I only upload .png files into the assets folder? I get an error for .svg files. I want to use it for the Image() component

like image 213
seref Avatar asked Oct 01 '19 23:10

seref


3 Answers

You can use Macaw to display a SVG: https://github.com/exyte/Macaw

1) Add the Package via SPM to your project (the tag 0.9.5 actually doesn't work, you need to use the master branch)

2) Move your .svg-file to the project or create a new Data set in your Assets.xcassets and then add the svg file to this data set.

3) Use this code:

struct MyView: View {

    var svgName: String

    var body: some View {
        SVGImage(svgName: self.svgName)
            .frame(width: 50, height: 550)
    }
}
struct SVGImage: UIViewRepresentable {

    var svgName: String

    func makeUIView(context: Context) -> SVGView {
        let svgView = SVGView()
        svgView.backgroundColor = UIColor(white: 1.0, alpha: 0.0)   // otherwise the background is black
        svgView.fileName = self.svgName
        svgView.contentMode = .scaleToFill
        return svgView
    }

    func updateUIView(_ uiView: SVGView, context: Context) {

    }

}
like image 197
Lupurus Avatar answered Oct 01 '22 08:10

Lupurus


I've created a simple tool, which converts SVG code into SwiftUI's Shape object. It is very limited for now (in particular it only supports straight lines and cubic curves, single path SVGs and shapes that are filled with one color), but you can still use it for simple situations.

Here's the link to the tool, and the repository, in case you'd want to contribute and make it support all SVG features.

like image 23
Antoni Silvestrovič Avatar answered Oct 01 '22 06:10

Antoni Silvestrovič


You can import svg images too in XCAssets. Go to XCAssets, click on + button. Refer this image

Click on import & select svg image.

Now to load & display that image use below code :

Image(uiImage: UIImage(named: "imageName")!)

like image 32
Rushabh Singh Avatar answered Oct 01 '22 06:10

Rushabh Singh