首页 > 解决方案 > 如何在视图边框的随机位置上绘制圆圈

问题描述

请帮助我了解如何在视图边框的随机位置上绘制圆圈。

红色视图选项

.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 选项在随机位置的红色视图上添加圆圈,但您可以看到它不起作用:

界

主要问题是如何知道任何设备上红色视图的宽度和高度并设置圆圈的位置。

标签: iosswiftswiftui

解决方案


您可以使用 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)
    }
    
}

在此处输入图像描述


推荐阅读