使用按钮大小制作背景图像比例

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

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

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; } } 

并以forms:

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

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

简单的编程方式

假设我有一个按钮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(只是为了确保您正确添加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; } } 

现在,当您将图像尺寸调整到适合其新尺寸的任何位置时,您将调整按钮的大小。

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

我使用此方法来避免对新类和事件处理程序进行任何其他编码。 这有助于我避免将所有Button对象转换为Image对象。

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

  2. 单击您选择的按钮。

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

  4. 导航到BackgroundImageLayout属性,然后选择Stretch

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

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

  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或其他具有更多缩放选项的控件