Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load SVG String to UIImage (Swift)

Tags:

xcode

swift

svg

I have a SVG Data downloaded from Internet in SVG format.

<svg viewBox="0 0 600 450" xmlns="http://www.w3.org/2000/svg"><rect x="0" y="0" width="600" height="450" fill="#E9F0FC"></rect><g transform="translate(0,410)" fill="none" font-size="10" font-family="sans-serif" text-anchor="middle" style="font-size: 8px;"><g class="tick" opacity="1" transform="translate(49.5,0)"><text fill="currentColor" ...

And I have a UIImageView where I would like to show picture from this data.

I was looking for some tutorials, but most of them are outdated or for objective-c.

I tried this

SVGImageView.image = UIImage(data: svgData)

But it says that I can't convert String to Data

like image 954
Marcel Kopera Avatar asked Jan 23 '26 04:01

Marcel Kopera


1 Answers

You can use SVGKit for example.

  1. Install it using CocoaPods.

    pod 'SVGKit'
    
  2. Use it like this:

     let svgImage = SVGKImage(data: yourSVGData)
    
     testImage.image = svgImage.UIImage
    

The framework also allows to init an SVGKImage from other different sources, for example it can download image for you when you provide it with URL.

like image 66
Ali Hamza Avatar answered Jan 25 '26 16:01

Ali Hamza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!