110,499
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 获取多边形内随机坐标点
/// </summary>
/// <param name="count">获取左边点数量</param>
/// <param name="point">多边形的各个点</param>
/// <returns></returns>
public Point[] GetPointInPolygon(int count, Point[] point)
{
if (point.Length < 3)
return null; //不是多边形
int x1 = int.MaxValue;
int x2 = int.MinValue;
int y1 = int.MaxValue;
int y2 = int.MinValue;
foreach (Point p in point)
{
if (p.X < x1)
x1 = p.X;
if (p.X > x2)
x2 = p.X;
if (p.Y < y1)
y1 = p.Y;
if (p.Y > y2)
y2 = p.Y;
}
GraphicsPath myGraphicsPath = new GraphicsPath();
Region myRegion = new Region();
myGraphicsPath.Reset();
myGraphicsPath.AddPolygon(pParam);
myRegion.MakeEmpty();
myRegion.Union(myGraphicsPath);
Random rnd = new Random((int)DateTime.Now.Ticks);
Point[] pointRet = new Point[count];
int n=0;
while(n<count)
{
Point p = new Point(rnd.Next(x1, x2), rnd.Next(y1, y2));
if (myRegion.IsVisible(p)) //在多边形内
{
pointRet[n] = p;
n++;
}
}
return pointRet;
}
private void Form1_Load(object sender, EventArgs e)
{
Point[] pParam = new Point[] { new Point(12, 34), new Point(3, 5), new Point(45, 56), new Point(126, 6) };
Point[] pIn = GetPointInPolygon(2, pParam);
}
/// <summary>
/// 获取多边形内随机坐标点
/// </summary>
/// <param name="count">获取左边点数量</param>
/// <param name="point">多边形的各个点</param>
/// <returns></returns>
public Point[] GetPointInPolygon(int count, Point[] point)
{
if (point.Length < 3)
return null; //不是多边形
int x1 = int.MaxValue;
int x2 = int.MinValue;
int y1 = int.MaxValue;
int y2 = int.MinValue;
foreach (Point p in point)
{
if (p.X < x1)
x1 = p.X;
if (p.X > x2)
x2 = p.X;
if (p.Y < y1)
y1 = p.Y;
if (p.Y > y2)
y2 = p.Y;
}
Random rnd = new Random((int)DateTime.Now.Ticks);
Point[] pointRet = new Point[count];
for (int i = 0; i < count; i++)
{
pointRet[i] = new Point(rnd.Next(x1, x2), rnd.Next(y1, y2));
}
return pointRet;
}