首页 > 解决方案 > 在视图中绘制多个圆圈 | 为每个

问题描述

我想要达到的目标

我学得很快。我正在尝试绘制一条带有多个圆圈的线。然后我希望能够在用户点击圆圈时修改圆圈的颜色。并最终进行拖放以移动圆圈。例如自定义贝塞尔曲线。

目前,我一直在画多个圆圈。

我想做什么:

1 - 我创建一个包含 CGPoint 的数组

public var PointArray:[CGPoint]=[]

2 - 然后做一个可识别的结构

private struct Positions: Identifiable {
    var id: Int
    let point: CGPoint
}

3 - 使用 CurveCustomInit,我填充了数组。我收到了这个错误

No exact matches in call to instance method 'append'

我做了很多,但我从来没有成功地在一个视图中使用 ForEach 函数。我正在使用结构形状,因为我想自定义形状然后重用组件。并且还为每个圆圈添加了手势功能。

有完整的代码:

请注意,GeometryReader 正在发送视图的大小

import SwiftUI

public var PointArray:[CGPoint]=[]
public var PointArrayInit:Bool = false

private struct Positions: Identifiable {
    var id: Int
    let point: CGPoint
}

struct Arc: Shape {
    var startAngle: Angle
    var endAngle: Angle
    var clockwise: Bool
    var centerCustom:CGPoint

    func path(in rect: CGRect) -> Path {
        let rotationAdjustment = Angle.degrees(90)
        let modifiedStart = startAngle - rotationAdjustment
        let modifiedEnd = endAngle - rotationAdjustment

        var path = Path()
        path.addArc(center: centerCustom, radius: 20, startAngle: modifiedStart, endAngle: modifiedEnd, clockwise: !clockwise)

        return path
    }
}

struct CurveCustomInit: Shape {
    private var Divider:Int = 10

    func path(in rect: CGRect) -> Path {
        var path = Path()
        let xStep:CGFloat = DrawingZoneWidth / CGFloat(Divider)
        let yStep:CGFloat = DrawingZoneHeight / 2
        var xStepLoopIncrement:CGFloat = 0
        path.move(to: CGPoint(x: 0, y: yStep))
        var incr = 0
        for _ in 0...Divider {
            let Point:CGPoint = CGPoint(x: xStepLoopIncrement, y: yStep)
            let value = Positions(id:incr, point:Point )
            PointArray.append(value)
            path.addLine(to: Point)
            xStepLoopIncrement += xStep
            incr += 1
        }
        
        PointArrayInit = true
        return (path)
    }
}

struct TouchCurveBasic: View {
    var body: some View {
        if !PointArrayInit {
            // initialisation
            CurveCustomInit()
                .stroke(Color.red, style: StrokeStyle(lineWidth: 10, lineCap: .round, lineJoin: .round))
                .frame(width: 300, height: 300)
                .overlay(Arc(startAngle: .degrees(0),endAngle: .degrees(360),clockwise:true).stroke(Color.blue, lineWidth: 10))
        } else {
            // Update point
        }
    }
}

struct TouchCurveBasic_Previews: PreviewProvider {
    static var previews: some View {
        TouchCurveBasic()
    }
}

我想要达到的目标:

在此处输入图像描述

标签: swiftswiftui

解决方案


您的数组PointArray包含 type 的值,CGFloat但您正在尝试附加 type 的值Positions。这就是您收到此错误的原因。


推荐阅读