单击按钮时,按钮图像与文本不对齐

本文关键字:按钮 文本 对齐 图像 单击 | 更新日期: 2023-09-27 18:21:36

我在.NET中遇到了一个关于按钮上的图像的令人恼火的问题。它们的行为不像你所期望的那样。

在按钮的属性中,可以设置"图像"。所以我选择了一个图像,图像就会显示在按钮上!到目前为止还不错。当单击按钮或处于按下状态时,按钮的文本将向下和向右移动一个像素以创建深度。但不是图像!它会保持在同一个位置,看起来会很奇怪。还有BackgroundImage属性,但情况更糟!因为如果我将BackgroundImageLayout设置为None而不是Center,当按下时,图像将向上和向左移动,与文本完全相反!怎么了?

无论如何,我想要实现的是一个按钮图像,它的移动就像按钮处于按下状态时文本的移动一样。有办法做到这一点吗?

单击按钮时,按钮图像与文本不对齐

只需制作一个新图像,并以偏移量粘贴原始图像。然后将其设置为ButtonImage

示例:

private void button1_MouseDown(object sender, MouseEventArgs e)
{
    // replace "button_image.png" with the filename of the image you are using
    Image normalImage = Image.FromFile("button_image.png");
    Image mouseDownImage = new Bitmap(normalImage.Width + 1, normalImage.Height + 1);
    Graphics g = Graphics.FromImage(mouseDownImage);
    // this will draw the normal image at an offset on mouseDownImage
    g.DrawImage(normalImage, 1, 1); // offset is one pixel each for x and y
    // clean up
    g.Dispose();
    button1.Image = mouseDownImage;
}
private void button1_MouseUp(object sender, MouseEventArgs e)
{
    // reset image to the normal one
    button1.Image = Image.FromFile("button_image.png");
}

编辑:以下功能修复了一个问题,即当鼠标按钮仍被按下时,光标离开按钮区域时,图像不会"弹出"回来(请参阅下面的劳工评论):

private void button1_MouseMove(object sender, MouseEventArgs e)
{
    Point relMousePos = e.Location;
    bool mouseOverButton = true;
    mouseOverButton &= relMousePos.X > 0;
    mouseOverButton &= relMousePos.X < button1.Width;
    mouseOverButton &= relMousePos.Y > 0;
    mouseOverButton &= relMousePos.Y < button1.Height;
    if (mouseOverButton != MouseButtons.None)
    {
        button1_MouseDown(sender, e);
    }
    else
    {
        button1_MouseUp(sender, e);
    }
}