How to keep moving PictureBox in boundaries C# Visual Studio 2010

允我心安 提交于 2020-01-06 14:33:31

问题


I am writing a bouncing logo screensaver in Visual Studio 2010 using C#. I have never written in C# before today so I am apologizing for any ignorance in advanced. I am importing an image to the form using PictureBox. Is there a way to find the boundaries of the PictureBox so I can compare it to the boundaries of the screen (using screen.Bounds for screen boundaries)? Like I said, I've never programmed in C# before so I am not sure what other details you will need, if any. Please let me know and I'll put up whatever I can. Thank you.

EDIT: My bounce method is written in public partial class ScreensaverForm. The frame is in static class Program. My boundary check in the bounce method is if(picturebox.Bounds.Bottom == this.Bounds.Bottom). This seems to check for boundaries, but the boundaries are not the boundaries of the frame. How do I call the frame attributes?


回答1:


Unless I'm missing something.

Get the Screenbounds as a Rectangle.

screenrectangle.Contains(new Rectangle(MyPictureBox.Location, MyPictureBox.Size))

will give you true if it's all on screen.




回答2:


Your picturebox will live in a form. The picturebox has a Bounds which provides you the top, left, right, and bottom values relative to the form in which it is contained. From there, you can easily calculate if the picturebox is completely within the form or not using the Forms width and height property, assuming that the top left corner is 0,0. As you move the picturebox, you check to ensure that the move you are about to do will keep the picturebox within the form.




回答3:


In addition to Tony's excellent suggestion, I would like to adress how to handle collision:

There are four boundaries, so there are four situations to check.

It is possible to have a horizontal and vertical bounce at the same time! Therefore keep track of horizontal and vertical speed independently, a horizontal bounce will only affect horizontal motion.

In addition, if your object moves more than one pixel at a time, you may not see an exact hit. (Like that the x coordinate of your box moves directly from 1 to -1 without being 0. So you should test if the boundary is on or over the boundary, not just test for on.

It is also good practice to only check for collision when you move towards a particular boundary. If you don't your window might get stuck because it collides with the same edge after every move.



来源:https://stackoverflow.com/questions/9537906/how-to-keep-moving-picturebox-in-boundaries-c-sharp-visual-studio-2010

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!