c# - 如何使用随机在 pictureBox1 中心 + 10 中绘制点?

标签 c#

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

但我想首先计算(我需要学习如何做)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();
        }

最佳答案

试试这个。它将计算距中心 +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

关于c# - 如何使用随机在 pictureBox1 中心 + 10 中绘制点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9412252/

相关文章:

javascript - SelectedIndexChange 事件处理程序代码

c# - 使用绑定(bind)重定向升级两个项目之一

c# - 如何让 Storyboard淡入、暂停然后淡出(通过代码)?

c# - 重定向时授权 header 丢失

c# - NewtonSoft JsonConvert 列表

C# 返回类中所有必需属性的列表

C#-Like Delegates in C++

c# - 从CheckedListBox获取CheckBox的标签文本

c# - 在 ASP.NET/MVC 中验证复杂情况的最佳实践?

c# - C# 中的内存问题,如果 .Net 应用程序调用 dll,则可以正常使用,但如果从旧版应用程序调用 dll,则内存问题为天文数字