如何使用Random在pictureBox1 center + 10中绘制点?

时间:2012-02-23 11:35:56

标签: c#

每次点击按钮时,我都有这个简单的代码,它在pictureBox1中的位置100,100处绘制一个点

但我想首先计算(我需要学习如何操作)pictureBox1的中心。

然后我想使用随机,所以每次我点击按钮它会从pictureBox1中心位置+10

画一个点randomaly
private void button5_MouseClick(object sender, MouseEventArgs e)
        {
            Random rnd = new Random();
            drawPoint(100, 100);
        }

        public void drawPoint(int x, int y)
        {
         Graphics g = Graphics.FromHwnd(pictureBox1.Handle);
         SolidBrush brush = new SolidBrush(Color.LimeGreen);
         Point dPoint = new Point(x, (pictureBox1.Height - y));
         dPoint.X = dPoint.X - 2;
         dPoint.Y = dPoint.Y - 2;
         Rectangle rect = new Rectangle(dPoint, new Size(4, 4));
         g.FillRectangle(brush, rect);
         g.Dispose();
        }

1 个答案:

答案 0 :(得分:2)

试试这个。它将计算从中心的随机偏移量+10 -10

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var halfX = pictureBox1.ClientRectangle.Width / 2;
            var halfY = pictureBox1.ClientRectangle.Height / 2;

            Random rnd = new Random();
            var offsetX = rnd.Next(-10, 10);
            var offsetY = rnd.Next(-10, 10);

            drawPoint(halfX + offsetX, halfY + offsetY);
        }

        public void drawPoint(int x, int y)
        {
            Graphics g = Graphics.FromHwnd(pictureBox1.Handle);
            SolidBrush brush = new SolidBrush(Color.LimeGreen);
            Point dPoint = new Point(x, (pictureBox1.Height - y));
            dPoint.X = dPoint.X - 2;
            dPoint.Y = dPoint.Y - 2;
            Rectangle rect = new Rectangle(dPoint, new Size(4, 4));
            g.FillRectangle(brush, rect);
            g.Dispose();
        }
     }

Result