我创建了一个与父级大小相同的分层视图(使用 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
有谁知道如何缩放源图像以适应框架?