根据布局方向翻转SwiftUI形状

6
我创建了一个SemiRoundedRectangle形状,用于剪裁侧边菜单。如果用户使用RTL语言,需要翻转该形状,但不确定最佳方法是什么。
我尝试过使用`.flipsForRightToLeftLayoutDirection(true)`,但这也会翻转阿拉伯文本。当我尝试旋转该形状时,它不再符合Shape协议,因此我无法在.clipShape中使用它。在SwiftUI中的其他所有内容都会在切换到阿拉伯语时自动翻转,是否有什么东西可以添加到我的形状中,使其也具有这些神奇的功能?
谢谢你的帮助 :)

import SwiftUI

struct SemiRoundedRectangle: Shape {
    var cornerRadius: CGFloat
    func path(in rect: CGRect) -> Path {
        var path = Path()
        path.move(to: CGPoint(x: rect.maxX, y: rect.minY))
        path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
        path.addLine(to: CGPoint(x: rect.minX+cornerRadius, y: rect.maxY))
        path.addArc(center: CGPoint(x: cornerRadius, y: rect.height - cornerRadius),
                    radius: cornerRadius,
                    startAngle: .degrees(90),
                    endAngle: .degrees(180), clockwise: false)
        path.addLine(to: CGPoint(x: 0, y: cornerRadius))
        path.addArc(center: CGPoint(x: cornerRadius, y: cornerRadius),
                    radius: cornerRadius,
                    startAngle: .degrees(180),
                    endAngle: .degrees(270), clockwise: false)
        path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
        
        return path
    }

}

struct TestView {
    var body: some View {
        HStack {
            Text("ايه الأخبار؟")
            .padding()
            .background(Color.green)
            .clipShape(SemiRoundedRectangle(cornerRadius: 10.0))
            
            Spacer()
        }
        
    }
}
3个回答

2
尝试将clipShape附加到Color.green上:
struct TestView: View {
    var body: some View {
        HStack {
            Text("ايه الأخبار؟")
            .padding()
            .background(
                Color.green /// here!
                    .clipShape(SemiRoundedRectangle(cornerRadius: 10.0))
                    .flipsForRightToLeftLayoutDirection(true)
            )
            
            Spacer()
        }
    }
}

结果:

英语 RTL 语言
屏幕左侧带左圆角的绿色矩形 屏幕右侧带右圆角的绿色矩形

0

有一个通用的解决方案:

extension Shape {
    func flipped(_ axis: Axis = .horizontal, anchor: UnitPoint = .center) -> ScaledShape<Self> {
        switch axis {
        case .horizontal:
            return scale(x: -1, y: 1, anchor: anchor)
        case .vertical:
            return scale(x: 1, y: -1, anchor: anchor)
        }
        
    }
}

在这种情况下使用:

struct TestView: View {
    var body: some View {
        HStack {
            Text("ايه الأخبار؟")
                .padding()
                .background(Color.green)
                .clipShape(SemiRoundedRectangle(cornerRadius: 20.0).flipped())
            Spacer()
        }
        .padding()
    }
}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接