2016-12-12 73 views
-3

我想随机绘制多个圆 - 不会重叠。为此,我想创建一个存储圆半径和x和y位置(这些是随机的)的对象。然后,我想将这些对象添加到数组以稍后计算一个圆与任何其他圆重叠。将多个值+名称存储在一个对象中

我知道,在p5.js的Javascript代码看起来像下面这样:

var circles = []; 
for (var i = 0; i < 30; i++) { 
    var circle = { 
    x: random(width), 
    y: random(height), 
    r: 32 
    }; 
    circles.push(circle); 
} 

//and now I can draw the circles like following but in a loop: 

ellipse(circles[i].x, circles[i].y, circles[i].r*2, circles[i].r*2); 

有没有办法在C#这样做吗?

+0

您可以使用[Ellipse](https://msdn.microsoft.com/en-us/library/system.windows.shapes.ellipse(v = vs.110).aspx)或编写自己的类。 –

+7

是的,有方法可以在C#中完成:) – Auguste

+0

在VS表单项目上,工具箱有一个可以使用的椭圆形的Visual Basic Power Packs。椭圆形的尺寸宽度和尺寸高度可以相等,形成一个圆圈。所以你可以有一个列表 circles = new List (); – jdweng

回答

2

就做这样的事情:

public class Circle 
    { 
     // In C# this is called a "property" - you can get or set its values 
     public double x { get; set; } 

     public double y { get; set; } 

     public double r { get; set; } 
    } 

    private static List<Circle> InitializeList() 
    { 
     Random random = new Random(); 

     List<Circle> listOfCircles = new List<Circle>(); 

     for (int i = 0; i < 30; i++) 
     { 
      // This is a special syntax that allows you to create an object 
      // and initialize it at the same time 
      // You could also create a custom constructor in Circle to achieve this 
      Circle newCircle = new Circle() 
      { 
       x = random.NextDouble(), 
       y = random.NextDouble(), 
       r = random.NextDouble() 
      }; 

      listOfCircles.Add(newCircle); 
     } 

     return listOfCircles; 
    } 

逻辑屏幕将取决于是否你正在做的Windows窗体,ASP.NET,WPF,或任何对实际绘制这一点,但你会这样做:

foreach (Circle circle in InitializeList()) 
{ 
    // This'll vary depending on what your UI is 
    DrawCircleOnScreen(circle); 
} 
1
class Circle { 
    public double Radius { get; set; } 
    public Vector2 Position { get; set; } 
} 

class Vector2 { 
    public double X { get; set; } 
    public double Y { get; set; } 
} 

在C#类阅读起来。

相关问题