C#生成随机多边形
生成随机多边形方法。
大体思路,生成一个正多边形,后将其利用随机数做微调,产生形变。
建立一个picturebox和一个button 使用自定义name。在buttonclick事件中进行如下处理
代码如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace random_duobianxing { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { int count = 8;//多边形边数、 double arc = 2 * Math.PI / count;//计算角度 int x = pictureBox1.Width / 2; int y = pictureBox1.Height / 2; //确定多边形的位置 Random ra = new Random(); List<Point> pointlist = new List<Point>();//存放点的集合 for (int i = 0; i < count; i++) { double curArc = arc * i; Point pt = new Point(); pt.X = x + ra.Next(-10, 10) + (int)(80 * Math.Cos(curArc));//添加偏移量 pt.Y = y + ra.Next(-10, 10) + (int)(80 * Math.Sin(curArc)); pointlist.Add(pt); } Graphics g = pictureBox1.CreateGraphics(); //画图 g.Clear(Color.White); Pen pen = new Pen(Color.Red, 3); g.DrawPolygon(pen, pointlist.ToArray()); } } }
需要注意的是:当偏移量合适既可以产生凹多边形,但是不能确保每一次都是生成的凹多边形。当偏移量过大时,可能导致多边形在内部相交,即生成了一个错误的。所以用这个算法需要注意偏移量。
浙公网安备 33010602011771号