UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Normalising SVG or UIBezierPath for use in SwiftUI Shape

Forums > SwiftUI

In a recent HWS+ article, Paul talks about using a normalised UIBezierPath (coordinates between 0 and 1) when creating a custom Shape in SwiftUI.

I have some SVG icons that I would be keen to use as SwiftUI Shape objects, but they are not normalised and have a viewbox size.

Once I have the normalised values, I can use a tool like SwiftVG to convert to a UIBezierPath.

However, I could not find a simple way of normalising them, even in vector-editing software. In the end I used a node.js package via the command line, but I still had to extract the viewbox and path data manually.

Is there an easier way?

3      

It's not required that you normalize your path first before using it. You can simply scale it on the spot to fit the rect it's supposed to fit into (generally the CGRect passed into the Shape's path() function). Here's an extension on Path that'll do that for you.

extension Path {
    func scaled(toFit rect: CGRect) -> Path {
        let scaleW = rect.width/boundingRect.width
        let scaleH = rect.height/boundingRect.height
        let scaleFactor = min(scaleW, scaleH)
        return applying(CGAffineTransform(scaleX: scaleFactor, y: scaleFactor))
    }
}

and the call site:

struct MyShape(myCustomBezier: UIBezierPath) : Shape {
   var myCustomBezier : UIBezierPath
   func path(in rect: CGRect) -> Path {
       let path = Path(myCustomBezier.cgPath)
       return path.scaled(toFit: rect)
   }
}

4      

I just realized that you've probably misunderstood some of what Paul was saying. You don't normalize your SVG's before running them through swiftvg; it's the other way around. Drop your SVG's into swiftvg just the way they are, and take the UIBezier-instantiating code that's output and paste it into your Xcode project. It's only then that you would normalize it. Although as I'm saying above, it's strictly speaking not necessary that you do that.

Stewart Lynch has produced a YouTube video based on Paul's article that walks you through the whole process: SwiftUI - SVG to UIBezierPath with Animation.

4      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.