0

I'm having a rather irritating problem with images on buttons in .NET. They don't behave as you would expect an image on a button to behave.

In the properties of a button you can set Image. So I select an image and the image shows up on the button! So far so good. When a button is clicked, or in a pressed state, the text of the button will move down and right one pixel to create a depth. But not the image! It will stay in the same position, and it will look weird. There is also the BackgroundImage property, but that's even worse! Because if I set BackgroundImageLayout to None instead of Center, the image will move up and left when pressed, the complete opposite direction of the text! What's up with that?

Anyway, what I want to achieve is a button image that moves just like the text would move when the button is in a pressed state. Is there a way to do this?

4

1 回答 1

0

只需制作一个新图像并将原始图像粘贴到偏移处即可。然后将其设置为Button's Image

例子:

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);
    }
}
于 2013-07-07T19:50:22.783 回答