gpt4 book ai didi

ios - 以编程方式绘制的圆圈没有出现 SwiftUI

转载 作者:行者123 更新时间:2023-12-04 08:48:55 33 4
gpt4 key购买 nike

我正在尝试使用 SwiftUI 创建一个测试应用程序,用户可以在其中拖动屏幕时在屏幕上绘图。但是,让我用来表示笔的圆圈出现时遇到了一些困难。
这是我正在使用的 ContentView.swift 代码。

import SwiftUI

var list_of_points = [CGPoint]()

struct ContentView: View {
var body: some View {
ZStack{
Rectangle().fill(Color.gray)
Text("Hello!")
}.gesture(DragGesture().onChanged({
value in
drag_responder(point: value.location)

}))
}
}

func drag_responder(point: CGPoint){
print("Drawing at \(point)")

list_of_points.append(point)
let pen = Circle().size(CGSize(width:10, height:10)).position(point)
pen
}


struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

最佳答案

import SwiftUI

struct Drawing {
var points: [CGPoint] = [CGPoint]()
}

struct ContentView: View {
@State private var currentDrawing: Drawing = Drawing()
@State private var drawings: [Drawing] = [Drawing]()
@State private var color: Color = Color.black
@State private var lineWidth: CGFloat = 3.0

var body: some View {
VStack(alignment: .center) {
DrawingPad(currentDrawing: $currentDrawing,
drawings: $drawings,
color: $color,
lineWidth: $lineWidth)
}
}
}

struct DrawingPad: View {
@Binding var currentDrawing: Drawing
@Binding var drawings: [Drawing]
@Binding var color: Color
@Binding var lineWidth: CGFloat

var body: some View {
GeometryReader { geometry in
Path { path in
for drawing in self.drawings {
self.add(drawing: drawing, toPath: &path)
}
self.add(drawing: self.currentDrawing, toPath: &path)
}
.stroke(self.color, lineWidth: self.lineWidth)
.background(Color(white: 0.95))
.gesture(
DragGesture(minimumDistance: 0.1)
.onChanged({ (value) in
let currentPoint = value.location
if currentPoint.y >= 0
&& currentPoint.y < geometry.size.height {
self.currentDrawing.points.append(currentPoint)
}
})
.onEnded({ (value) in
self.drawings.append(self.currentDrawing)
self.currentDrawing = Drawing()
})
)
}
.frame(maxHeight: .infinity)
}

private func add(drawing: Drawing, toPath path: inout Path) {
let points = drawing.points
if points.count > 1 {
for i in 0..<points.count-1 {
let current = points[i]
let next = points[i+1]
path.move(to: current)
path.addLine(to: next)
}
}
}

}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

关于ios - 以编程方式绘制的圆圈没有出现 SwiftUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64176722/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com