简体   繁体   中英

How to move the button inside the pictureBox1 without leave the pictureBox area?

private void timer1_Tick(object sender, EventArgs e)
        {
            int x = r.Next(0, pictureBox1.Width);
            int y = r.Next(0, pictureBox1.Height);
            button1.Top = y;
            button1.Left = x;
        }

        private void button2_Click(object sender, EventArgs e)
        {

        }

EDIT**

int x1 = r.Next(0, pictureBox1.Width);
            int y1 = r.Next(0, pictureBox1.Height);
            randomPoint = new Point(x1, y1);
            if (currentPosition.X != randomPoint.X)
            {
                if (currentPosition.X > randomPoint.X)
                    currentPosition.X -= 1;
                else
                    currentPosition.X += 1;

                button1.Location = currentPosition;
            }
            else if (currentPosition.Y != randomPoint.Y)
            {
                if (currentPosition.Y > randomPoint.Y)
                    currentPosition.Y -= 1;
                else
                    currentPosition.Y += 1;

                button1.Location = currentPosition;
            }
            else
            {
                randomPoint.X = r.Next(0, pictureBox1.Width - button1.Width - 1);
                randomPoint.Y = r.Next(0, pictureBox1.Height - button1.Height - 1);
            }

In top of the form i did:

int x ;
int y ;
Point currentPosition;
Point randomPoint;

In constructor:

x = button1.Location.X; y = button1.Location.Y; currentPosition = new Point(x, y);

In your form load event do:

currentPosition = button1.Location;
randomPoint.X = r.Next(0, PictureBox1.Width - Button1.Width - 1);
randomPoint.Y = r.Next(0, PictureBox1.Height - Button1.Height - 1);

Inside your timer:

if(currentPosition.X != randomPoint.X){
    if (currentPosition.X > randomPoint.X)
        currentPosition.X -= 1;
    else
        currentPosition.X += 1;

    Button1.Location = currentPosition;
}
else if(currentPosition.Y != randomPoint.Y){
    if(currentPosition.Y > randomPoint.Y)
        currentPosition.Y -= 1;
    else
        currentPosition.Y += 1;

    Button1.Location = currentPosition;
}
else{
    randomPoint.X = r.Next(0, PictureBox1.Width - Button1.Width - 1);
    randomPoint.Y = r.Next(0, PictureBox1.Height - Button1.Height - 1);
}

As far as the movement, you can increase picturebox size or(and) dicrease button size. Dont forget to declare Random r = new Random(); where you declared currentPosition and randomPoint .

valter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM