mchoe / SwiftSVG

A simple, performant, and lightweight SVG parser
Other
1.92k stars 229 forks source link

How to center SVG layer? #138

Open changelee82 opened 5 years ago

changelee82 commented 5 years ago

Hello! I create a UIImageView extension, but SVG layer is not center.

    let _ = CALayer(SVGURL: url) { (svgLayer) in
        svgLayer.resizeToFit(self.bounds)
        self.layer.addSublayer(svgLayer)
    }

center2

I found that the file contained viewBox="0 0 100 100", So I tried to add a line of code.

    let _ = CALayer(SVGURL: url) { (svgLayer) in
        svgLayer.boundingBox = CGRect(x: 0, y: 0, width: 100, height: 100)
        svgLayer.resizeToFit(self.bounds)
        self.layer.addSublayer(svgLayer)
    }

center

`<svg version="1.1" id="p" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve">

<path id="XMLID_4_" d="M41.3,16.1c0.5-1.2,1.2-2.2,2-3c0.8-0.8,1.8-1.5,3-2c1.1-0.5,2.4-0.8,3.7-0.8c1.3,0,2.5,0.3,3.6,0.8
    c1.2,0.5,2.2,1.2,3,2c0.9,0.8,1.6,1.8,2.1,3c0.5,1.2,0.8,2.4,0.8,3.6c0,1.5-0.3,2.8-1,4.1c-0.7,1.3-1.6,2.4-2.7,3.3
    c3.6,1,6.5,2.8,8.6,5.3c2.2,2.5,3.3,5.4,3.3,8.6c0,2.7-0.8,5.1-2.3,7.3c-1.5,2.2-3.6,3.9-6.1,5.4c2.8,0.7,5.4,1.8,7.8,3.1
    c2.4,1.3,4.4,2.9,6,4.7c1.7,1.8,3,3.8,3.9,5.9c0.9,2.1,1.4,4.4,1.4,6.7v10.7H21.6V74c0-2.3,0.5-4.6,1.4-6.7c0.9-2.1,2.3-4.1,4-5.9
    s3.7-3.4,6.1-4.7c2.4-1.3,5-2.4,7.8-3.1c-2.7-1.4-4.8-3.2-6.3-5.4c-1.5-2.2-2.3-4.6-2.3-7.3c0-3.2,1.1-6.1,3.3-8.6
    c2.2-2.5,5.1-4.3,8.7-5.3c-1.1-0.9-2-2-2.7-3.3c-0.7-1.3-1-2.6-1-4.1C40.5,18.5,40.8,17.3,41.3,16.1z"/>

`

How to center other SVG layer? I want to get the viewBox in svg file to setting boundingBox of svgLayer.

samrayner commented 3 years ago

Here is how I get the viewBox dynamically from the SVG @changelee82. It's probably not the most performant solution but it works for me. Thankfully the viewBox attribute should appear very early on in the SVG source.

func viewBox(svgData: Data) -> CGRect? {
    guard let string = String(data: svgData, encoding: .utf8),
          let range = string.range(of: #" viewBox=\"([^"]+)\" "#, options: .regularExpression) else {
        return nil
    }

    let matchParts = string[range].components(separatedBy: "\"")

    guard matchParts.count == 3 else { return nil }

    let viewBox = matchParts[1].components(separatedBy: " ").compactMap(Int.init)

    guard viewBox.count == 4 else { return nil }

    return .init(x: viewBox[0], y: viewBox[1], width: viewBox[2], height: viewBox[3])
}