简体   繁体   English

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

[英]How to adjust CALayer size in order to fit the parent view

I created a layered view (SVGImageView using PocketSVG ) that has the same size as parent:我创建了一个与父级大小相同的分层视图(使用 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 is defined as follows: 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) {
        
    }
}

The problem is that the source SVG image is larger than the parent view and therefore only a part of it is visible.问题是源 SVG 图像大于父视图,因此只有一部分可见。 I would like the source image to fit the frame;我希望源图像适合框架; the same way it fits in case of UIImageView with the following settings:与 UIImageView 的情况相同,具有以下设置:

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

Does anyone know how to scale source image to fit the frame?有谁知道如何缩放源图像以适应框架?

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.如果这是 UIBezierPath,可以通过对其应用转换轻松完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM