6

我正在尝试向我的 Win Forms 应用程序中的几个按钮添加一些背景图像。这三个图像的大小不同(即像素尺寸不匹配,一个是 128x128,另一个是 256x256)。我需要按钮大小相同(否则 GUI 非常不对称)。在不更改实际图像文件的情况下,如何使图像随按钮大小缩放?

我尝试创建自己的类,并为按钮调整大小事件添加事件处理程序,但这似乎不起作用。我的代码:

class CustomButton : Button {

        internal void CustomButton_Resize( object sender, EventArgs e ) {
            if ( this.BackgroundImage == null ) {
                return;
            }

            var pic = new Bitmap( this.BackgroundImage, this.Width, this.Height );
            this.BackgroundImage = pic;
        }
    }

并采用以下形式:

this.buttonOne.Resize += new System.EventHandler(this.buttonOne.CustomButton_Resize);

忘了提一下,上面的代码根本没有调整图像的大小。按钮仍然需要具有不同的大小才能完全显示图像。

4

3 回答 3

14

将背景图像添加到 .NET Button 对象并将其缩放以适合的最简单方法

我使用这种方法来避免对新类和事件处理程序进行任何额外的编码。这也帮助我避免将所有 Button 对象转换为 Image 对象。

  1. 将图像添加到 Resources.resx 文件。

  2. 单击您选择的按钮。

  3. 导航到BackgroundImage属性并选择您导入到项目的 resources.resx 文件中的图像。

  4. 导航到BackgroundImageLayout属性并选择Stretch

确保您没有为ImageandText属性输入任何内容,否则它们会干扰您的新背景图像。

于 2013-09-06T23:35:54.563 回答
10

简单的程序化方式

假设我有一个按钮btn1,以下代码在 visual-studio-2010 中运行良好。

private void btn1_Click(object sender, EventArgs e)
{
    btn1.Width = 120;
    btn1.Height = 100;
}
void btn1_Resize(object sender, EventArgs e)
{
    if ( this.BackgroundImage == null )
          return;
    var bm = new Bitmap(btn1.BackgroundImage, new Size(btn1.Width, btn1.Height));
    btn1.BackgroundImage = bm;
}

更好的方法

您可以在自定义按钮的构造函数中添加 eventHandler(只是为了确保您正确添加事件处理程序)

class CustomButton : Button
{    
    CustomButton()
    {
        this.Resize += new System.EventHandler(buttonOne.CustomButton_Resize);
    }
    void CustomButton_Resize( object sender, EventArgs e )
    {
       if ( this.BackgroundImage == null )
          return;
       var pic = new Bitmap( this.BackgroundImage, new Size(this.Width, this.Height) );
       this.BackgroundImage = pic;          
    }
}

现在,当您在任何地方调整按钮大小时,您的图像将适合(缩放)到其新大小。

于 2012-11-13T12:41:51.987 回答
1

你可以从这样的事情开始......

 public class ImageButton : Control
{
    public Image backgroundImage;

    public Image BackgroundImage
    {
        get
        {
            return backgroundImage;
        }
        set
        {
            backgroundImage = value;
            Refresh();
        }
    }

    public ImageButton()
    {

    }

    protected override void OnPaint(PaintEventArgs e)
    {
        e.Graphics.Clear(BackColor);

        if(BackgroundImage != null)
            e.Graphics.DrawImage(BackgroundImage, 0, 0, Width, Height);

        base.OnPaint(e);
    }

    protected override void OnPaintBackground(PaintEventArgs pevent)
    {
        //base.OnPaintBackground(pevent);
    }
}

您可以自己处理油漆并绘制图像。您也可以尝试使用 PictureBox 或其他具有更多缩放选项的控件

于 2012-11-13T08:36:42.453 回答