简体   繁体   中英

How to center an image in a rectangle?

如何通过以下方式使图像居中于矩形内部:

Batch.draw(imagename, new Rectangle(x, y, imagename.width, imagename.height), Color.White);

您可以将原点重载用于spritebatch

Batch.draw(imagename, new Rectangle(x, y, imagename.width, imagename.height), Color.White,0f,new Vector2(imagename.Width /2, imagename.Height /2) ,SpriteEffects.Null, 0);

One of the overloads for SpriteBatch.Draw() asks for a Texture2D (the image), a Vector2 (the position of the image), and a Color (the tint of the image). You should not have to use a rectangle for drawing your image. Just use some math to get the correct X and Y values for the position.

You will have to take into consideration the height/width of the image, and the height/width of the containing object (like the screen or something).

Another option is to use an overload that takes the Origin parameter. Set this to the relative center of your image. This will change the "draw origin" of the image from the top-left to the center.

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