ios - 如何在视图边框的随机位置上绘制圆圈
问题描述
请帮助我了解如何在视图边框的随机位置上绘制圆圈。
红色视图选项
.background(Color.red)
.padding(40)
界:
var body: some View
{
Circle()
.strokeBorder(Color.blue, lineWidth: 2.0, antialiased: true)
.frame(width: 50, height: 50, alignment: .center)
.overlay(Text(title))
}
我尝试使用 .position 选项在随机位置的红色视图上添加圆圈,但您可以看到它不起作用:
主要问题是如何知道任何设备上红色视图的宽度和高度并设置圆圈的位置。
解决方案
您可以使用 GeometryReader 来读取 View 的大小,如示例中所示:
struct ContentView: View {
var body: some View {
GeometryReader { proxy in
ForEach(0...50, id:\.self) { index in
CirclesView(index: index)
.offset(x: CGFloat.random(in: 0.0...proxy.size.width), y: CGFloat.random(in: 0.0...proxy.size.height))
}
}
.background(Color.red)
.ignoresSafeArea()
}
}
struct CirclesView: View {
let index: Int
var body: some View {
Circle()
.strokeBorder(Color.blue, lineWidth: 2.0, antialiased: true)
.frame(width: 50, height: 50, alignment: .center)
.overlay(Text(String(describing: index)))
}
}
更新:
struct ContentView: View {
var body: some View {
GeometryReader { proxy in
ForEach(0...50, id:\.self) { index in
CirclesView(index: index, offset: logicalFunction(size: proxy.size))
}
}
.background(Color.red)
.ignoresSafeArea()
}
func logicalFunction(size: CGSize) -> CGSize {
// Do your works here!
let width: CGFloat = CGFloat.random(in: 0.0...size.width)
let height: CGFloat = CGFloat.random(in: 0.0...size.height)
return CGSize(width: width, height: height)
}
}
struct CirclesView: View {
let index: Int
let offset: CGSize
var body: some View {
Circle()
.strokeBorder(Color.blue, lineWidth: 2.0, antialiased: true)
.frame(width: 50, height: 50, alignment: .center)
.overlay(Text(String(describing: index)))
.offset(offset)
}
}
推荐阅读
- python - Python中字符串的相似性度量
- ibm-cloud - 所有者更改后如何更改工具链的git存储库
- python - 如何从终端/命令提示符启动 PyCharm
- sql - Oracle 中基于日期的行生成
- c# - Marshal.GetFunctionPointerForDelegate 上的 C# System.NotSupportedException
- python - 如何在 Python 中捕获 requests.POST 的结果?
- ios - 可以在 Xcode Simulator 中进行简单但独立的视图控制器 UI 测试吗?
- javascript - Dynamodb 批量写入删除请求不适用于分区和排序键
- android - 将位图图像转换为 Uri 不起作用
- angular - 我们如何在 Angular 中一个接一个地显示表单错误验证