繁体   English   中英

SwiftUI:使用 CGAffineTransform 缩放路径以适应视图

[英]SwiftUI: Using CGAffineTransform to scale a Path to fit a View

我有一个绘图,我是从它自己的结构中的一组 CGPoints(即 [[CGPoints]])生成的(结构本身有一些额外的数据)......我试图在我的视图中使用以下代码:

class Drawing: ObservableObject {

@Published private var lines = [Line]()
@Published var currentIndex = 0

public var visibleLines: [Line] {
        Array(lines.prefix(currentIndex))
    }

}

class Line: ObservableObject {

    var lineIndex = 0
    var points = [CGPoint]()
}


Struct View: View {

@Published var drawing = Drawing()


 func add(line: Line, to path: inout Path) {
            let points = line.points

            guard points.count > 1 else {
                return
            }

            for i in 0 ..< points.count - 1 {
                let current = points[i]
                let next = points[i + 1]
                path.move(to: current)
                path.addLine(to: next)
            }
            
            
        }

var body: some View {

GeometryReader { geometry in

 let frame = CGRect(x: geometry.frame(in: .local).minX, y: geometry.frame(in: .local).minY, width: geometry.frame(in: .local).width, height: geometry.frame(in: .local).height)

Path { path in
     for line in drawing.visibleLines {
      add(line: line, to: &path)
        }
     } 
     .scaled(for: frame)
     .stroke(Color.white, lineWidth: 2)
     .frame(alignment: .center) 
   }

 }
}

extension Path {
    func scaled(for rect: CGRect) -> Path {

        
        let scaleX = boundingRect.width/rect.width
        print("scaleX = \(scaleX)")
        let scaleY = boundingRect.height/rect.height
        print("scaleY = \(scaleY)")
        let scale = min(scaleX, scaleY)
        print("scale = \(scale)")
        return applying(CGAffineTransform(scaleX: scale, y: scale))
        
    }
}

我试图让绘图在视图中间尽可能大,但目前它很小并且随着用户向绘图添加点而放大。 我认为 CGAffineTransform 会缩放点以适应每个视图(通过我正在创建的 GeometryReader 框架),但它似乎相反。 我还尝试(在我的“缩放”修饰符中)将数学转换为 rect.width/boundingRect.width 和 rect.height/boundingRect.height,但该线在视图中不可见......

暂无
暂无

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

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