How to adjust CALayer size in order to fit the parent view

993 Views Asked by At

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?

1

There are 1 best solutions below

2
On

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.