SwiftUI画图之变化的花

SwiftUI画图之变化的花
首先定义一个shape类视图,画出花瓣
简单的解释见程序

struct Flower: Shape {
    // 花瓣偏离中心点数值
    var petalOffset: Double = -20

    // 花瓣的宽度
    var petalWidth: Double = 100

    func path(in rect: CGRect) -> Path {
        // The path that will hold all petals
        var path = Path()

        // 从0度到360度每180/8度移动一次
        for number in stride(from: 0, to: CGFloat.pi * 2, by: CGFloat.pi / 8) {
            // 旋转花瓣
            let rotation = CGAffineTransform(rotationAngle: number)

            
            let position = rotation.concatenating(CGAffineTransform(translationX: rect.width / 2, y: rect.height / 2))

            // 创建路径
            let originalPetal = Path(ellipseIn: CGRect(x: CGFloat(petalOffset), y: 0, width: CGFloat(petalWidth), height: rect.width / 2))

            
            let rotatedPetal = originalPetal.applying(position)

            // 添加路径到旋转花瓣中
            path.addPath(rotatedPetal)
        }

        // 返回路径
        return path
    }
}

然后在主视图中调用

@State private var petalOffset = -20.0
    @State private var petalWidth = 100.0
    
    var body: some View {
        VStack{
        Flower(petalOffset: petalOffset, petalWidth: petalWidth)
            //.stroke(Color.red, lineWidth: 1)
            .fill(Color.red, style: FillStyle(eoFill: true))

        Text("Offset")
        Slider(value: $petalOffset, in: -40...40).padding([.horizontal, .bottom])

        Text("Width")
        Slider(value: $petalWidth, in: 0...100).padding(.horizontal)
    }
    }

petalOffset,petalWidth作为Slider的参数用于调整花瓣,可以通过调整Slider

来改变图形。注意这两个值变化对图形产生的影响

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/jackwsd/article/details/107876543