How to add SVG icon in Swift?

23 min read

To add an SVG icon in Swift, you will first need to convert the SVG file to a CGPath. You can then use the CGPath to create a custom UIView or CALayer.

  1. Import the SVGKit framework in your project. SVGKit provides a set of classes to handle SVG files in iOS.
import SVGKit
  1. Load the SVG file and extract the CGPath from it.
// Load SVG file
let svgURL = Bundle.main.url(forResource: "icon", withExtension: "svg")!
let svgSource = SVGURLSource(url: svgURL)
let svgImage = SVGKImage(source: svgSource)

// Extract CGPath from SVG
let svgLayer = svgImage?.layer(withIdentifier: svgImage?.svgNamedLayers?[0].identifier)
let svgPath = svgLayer?.transformToCGPath()
  1. Create a custom UIView or CALayer that renders the SVG path.
class SVGIconView: UIView {
    var path: CGPath?
    
    override func draw(_ rect: CGRect) {
        if let context = UIGraphicsGetCurrentContext() {
            // Set fill color or stroke color
            context.setFillColor(UIColor.black.cgColor)
            // OR: context.setStrokeColor(UIColor.black.cgColor)
            
            // Draw the SVG path
            context.addPath(path!)
            context.fillPath()
            // OR: context.strokePath()
        }
    }
}

// Usage
let iconView = SVGIconView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
iconView.path = svgPath
  1. Add the custom view to your view hierarchy.
self.view.addSubview(iconView)

Note: SVGKit offers more advanced features to handle SVG files, such as scaling and manipulating individual elements within the SVG. You can explore the SVGKit documentation for additional functionality.