如何对不同形状使用同一组修改器

2024-03-19

作为我学习 SwiftUI 项目的一部分,我做了一些形状旋转,下面有代码。我想知道如何避免每个形状使用相同的三行修饰符。

func getShape(shape: Int, i: Int) -> AnyView {
    
    switch shape {
    case 0:
        return AnyView(Rectangle()
                        .stroke(colors[Int(shapeColor)])
                        .frame(width: CGFloat(shapeWidth), height: CGFloat(shapeHeight))
                        .rotationEffect(Angle(degrees: Double(i) * Double(angleStep))))
    case 1:
        return AnyView(Capsule()
                        .stroke(colors[Int(shapeColor)])
                        .frame(width: CGFloat(shapeWidth), height: CGFloat(shapeHeight))
                        .rotationEffect(Angle(degrees: Double(i) * Double(angleStep))))
    case 2:
        return AnyView(Ellipse()
                        .stroke(colors[Int(shapeColor)])
                        .frame(width: CGFloat(shapeWidth), height: CGFloat(shapeHeight))
                        .rotationEffect(Angle(degrees: Double(i) * Double(angleStep))))
    default:
        return AnyView(Rectangle()
                        .stroke(colors[Int(shapeColor)])
                        .frame(width: CGFloat(shapeWidth), height: CGFloat(shapeHeight))
                        .rotationEffect(Angle(degrees: Double(i) * Double(angleStep))))
        
    }
}

使用助手AnyShape类型橡皮擦

struct AnyShape: Shape {
    private let builder: (CGRect) -> Path

    init<S: Shape>(_ shape: S) {
        builder = { rect in
            let path = shape.path(in: rect)
            return path
        }
    }

    func path(in rect: CGRect) -> Path {
        return builder(rect)
    }
}

你的函数可以写成

func getShape(shape: Int, i: Int) -> some View {
    let selectedShape: AnyShape = {
        switch shape {
            case 0:
                return AnyShape(Rectangle())
            case 1:
                return AnyShape(Capsule())
            case 2:
                return AnyShape(Ellipse())
            default:
                return AnyShape(Rectangle())
        }
    }()
    return selectedShape
        .stroke(colors[Int(shapeColor)])
        .frame(width: CGFloat(shapeWidth), height: CGFloat(shapeHeight))
        .rotationEffect(Angle(degrees: Double(i) * Double(angleStep))))
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何对不同形状使用同一组修改器 的相关文章

随机推荐