2012-02-23 39 views
1

我这个简单的代码,每次我按一下按钮其在位置100,100我如何绘制pictureBox1中心点+10使用随机?

绘制在pictureBox1点,但我想首先计算(我需要学习如何做到这一点)的pictureBox1的中心。

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

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(); 
     } 
+0

当最小化会发生什么,然后还原形式?或者当你在窗体上拖动另一个程序的窗口时?此外,您需要处理您的SolidBrush – 2012-02-23 15:07:18

回答

2

试试这个randomaly画一个点。它会计算从中心随机偏移+ 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

+0

StaWho几乎将其绘制在pictureBox1顶部不在中心。有些点甚至我不能看到它们被绘制在pictureBox顶部,而不是在Form上出站,而是在pictureBox顶部。 – user1196715 2012-02-23 11:57:50

+0

奇怪,它对我来说没问题。发布更新与完整的应用程序列表,看看如果你没有做任何其他可能会影响绘图位置 – StaWho 2012-02-23 12:02:28

+0

其在mt form1中的其他工作还没有确定我试过你的代码在一个新的项目和它的工作完美。谢谢。 – user1196715 2012-02-23 12:12:59