如何在 SwiftUI 中水平翻转 Shape?

Eri*_*rik 1 swiftui

我有一个Shape需要沿x轴翻转。我正在寻找一种方法来解决这个问题CGAffineTransform,但我只找到了一种旋转形状的方法,但没有找到沿轴翻转的方法。我需要类似.rotation3DEffect(.degrees(180), axis: (x: 1, y: 0, z: 0))形状的东西

jn_*_*pdx 10

rotation3DEffect您可以在形状上使用。这是一个简单的例子:

struct ContentView : View {
    @State var degrees : Double = 0
    
    var body: some View {
        VStack {
            MyShape()
                .fill(Color.red)
                .rotation3DEffect(.degrees(degrees), axis: (x: 1, y: 0, z: 0))
            Button("Rotate") {
                withAnimation {
                    degrees = degrees == 0 ? 180 : 0
                }
            }
        }
    }
}

struct MyShape : Shape {
    func path(in rect: CGRect) -> Path {
        Path { path in
            path.move(to: .zero)
            path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
            path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

为了避免混淆,我想说你的问题标题和你的rotation3DEffect代码示例以及你的标题(“水平”翻转形状)在我的脑海中有点冲突——旋转 180 度执行axis(x:1, y:0, z:0)我认为的垂直翻转。对于水平方向,您可以将其更改为axis(x:0, y:1, z:0)


Pau*_*l B 5

这是返回 a 的方法Shape(我想说的是一些): Shape

extension Shape {  
    func flipped() -> ScaledShape<Self> {
        scale(x: -1, y: 1, anchor: .center)
    }
}
Run Code Online (Sandbox Code Playgroud)

如果需要一些更复杂的路径操作:

struct FlippedShape<Content>: Shape where Content : Shape {
    let content: Content
    func path(in rect: CGRect) -> Path {
        let flip = CGAffineTransform(scaleX: -1, y: 1)
        let position = flip.concatenating(CGAffineTransform(translationX: rect.width, y: 0))
        // some other path manipulation requiring `rect`
        return content.path(in: rect).applying(position)
    }
}

extension Shape {
    func flipped() -> FlippedShape<Self> {
        FlippedShape(content: self)
    }
}
Run Code Online (Sandbox Code Playgroud)