c# Xna通过精灵字体实现了一个下降的比例效果



所以我正在为我的游戏制作菜单。下面是一个按钮的代码:

// button class
public class ButtonGUI
{
    public SpriteFont spriteFont;
    string btnTxt;
    public Rectangle btnRect;
    Color colour;
    public ButtonGUI(string newTxt, Rectangle newRect, SpriteFont newSpriteFont, Color newColour)
    {
        spriteFont = newSpriteFont;
        btnRect = newRect;
        btnTxt = newTxt;
        colour = newColour;
    }
    public void Draw(SpriteBatch spriteBatch)
    {
        // TextOutliner() is a static helper class for drawing bordered spritefonts I made
        TextOutliner.DrawBorderedText(spriteBatch, spriteFont, btnTxt, btnRect.X, btnRect.Y, colour);
    }
}
// TitleScreen.cs
ButtonGUI btnPlay, btnPlay_2;
bool indexPlay;
string[] menuTxt;
SpriteFont GameFontLarge, GameFontLargeHover;
// LoadContent() method:
// Load both spritefonts....
menuTxt = new string[4];
menuTxt[0] = "Play Game";
menuTxt[1] = "Achievements";
menuTxt[2] = "Settings";
menuTxt[3] = "Exit Game";
btnPlay = new ButtonGUI(menuTxt[0], new Rectangle(150, 300, (int)GameFontLarge.MeasureString(menuTxt[0]).X, (int)GameFontLarge.MeasureString(menuTxt[0]).Y), GameFontLarge, Color.White);
btnPlay_2 = new ButtonGUI(menuTxt[0], new Rectangle(150, 300, (int)GameFontLargeHover.MeasureString(menuTxt[0]).X, (int)GameFontLargeHover.MeasureString(menuTxt[0]).Y), GameFontLargeHover, Color.Yellow);
// Update() method:
MouseState mouseState = Mouse.GetState();
Rectangle mouseRect = new Rectangle(mouseState.X, mouseState.Y, 1, 1);
if (mouseRect.Intersects(btnPlay.btnRect))
{
    indexPlay = true;
    if (mouseState.LeftButton == ButtonState.Pressed) Game1.CurrentGameState = Game1.GameState.playScreen;
}
else indexPlay = false;
// Draw() method:
if (indexPlay)
{
    btnPlay_2.Draw(spriteBatch);
}
else btnPlay.Draw(spriteBatch);

我为4个不同的按钮做了这些。2个精灵字体是相同的字体,但是的大小不同。现在当我测试游戏时,当我将鼠标悬停在每个按钮上时,文本就会从白色变为黄色并变得更大。但是,由于按钮坐标是用x = left-most; y = top-most完成的,当字体改变时,较大的字体被绘制在与较小的字体相同的位置。我想在鼠标悬停时得到一个不错的"缩放"效果。我的意思是,我知道我在初始化时设置了按钮位置,但我仍然需要某种算法来找到一种方法在旧的中间绘制更大的字体。你的方法是什么?

您可以根据大小差异更改悬停按钮的位置:

var sizeDifference = btnPlay_2.btnRect.Size - btnPlay.btnRect.Size;
btnPlay_2.btnRect.Offset(-sizeDifference.X/2, -sizeDifference.Y/2);

最新更新