-1

I created a layered view (SVGImageView using PocketSVG) that has the same size as parent:

var body: some View {
            GeometryReader { reader in
                SVGImageLayered("world", width: reader.size.width, height: reader.size.height)
                    .frame(width: reader.size.width, height: reader.size.height, alignment: .center)
...

SVGImageLayered is defined as follows:

struct SVGImageLayered: UIViewRepresentable {
    var resourcePath: String
    var frameWidth: CGFloat
    var frameHeight: CGFloat
    init(_ resourceName: String, width: CGFloat, height: CGFloat) {
        resourcePath = resourceName
        frameWidth = width
        frameHeight = height
    }
    func makeUIView(context: Context) -> UIView {
        let svgView = UIView(frame: UIScreen.main.bounds)
        let url = Bundle.main.url(forResource: resourcePath, withExtension: "svg")!
        
        let paths = SVGBezierPath.pathsFromSVG(at: url)
        let imageLayer = CALayer()
        for (index, path) in paths.enumerated() {
            let shapeLayer = CAShapeLayer()
            shapeLayer.path = path.cgPath
            imageLayer.addSublayer(shapeLayer)
        }
        imageLayer.frame = CGRect(x: 0, y: 0, width: frameWidth, height: frameHeight)
        svgView.layer.addSublayer(imageLayer)
        
        return svgView
    }
    func updateUIView(_ view: UIView, context: Context) {
        
    }
}

The problem is that the source SVG image is larger than the parent view and therefore only a part of it is visible. I would like the source image to fit the frame; the same way it fits in case of UIImageView with the following settings:

imageView.frame = svgView.bounds
imageView.contentMode = .scaleAspectFit

Does anyone know how to scale source image to fit the frame?

Niko Gamulin
  • 66,025
  • 95
  • 221
  • 286
  • This is not relevant, but do note that in iOS 14 you can use an SVG directly in the asset catalog and display it like any other image. – matt Jul 29 '20 at 20:29

1 Answers1

0

The problem is that you're using a shape layer. A shape layer has a path. The path knows nothing about the size of the layer! Even a zero-size shape layer will display its path exactly the same way.

What you need to adjust is the path. If this is a UIBezierPath, that's easily done by applying a transform to it.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Thank you. Still, I guess, somehow I have to read the size of the image to calculate the scale transform ratio in order to adjust the paths to fit the screen. – Niko Gamulin Jul 29 '20 at 20:44
  • Yes, my point is that no magic property of the layer is going to have any effect. The shape will be drawn according to the instructions you give. If you don't like its size, you will have either to change the instructions or not use a shape layer. – matt Jul 29 '20 at 20:46