如何调整CALayer大小以适合父视图

时间:2020-07-29 20:13:06

标签: ios swift swiftui pocketsvg

我创建了一个与父级具有相同大小的分层视图(使用PocketSVG的SVGImageView):

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定义如下:

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) {
        
    }
}

问题在于源SVG图像大于父视图,因此仅一部分可见。我希望源图像适合框架;具有以下设置的情况适用于UIImageView:

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

有人知道如何缩放源图像以适合框架吗?

1 个答案:

答案 0 :(得分:0)

问题是您正在使用形状图层。形状层具有路径。路径对图层的大小一无所知!甚至零尺寸的形状图层也将以完全相同的方式显示其路径。

您需要调整的是路径。如果这是UIBezierPath,可以通过applying a transform轻松完成。