C# 使用按钮大小制作背景图像比例
我正在尝试向Win Forms应用程序中的几个按钮添加一些背景图像。这三幅图像大小不同(即像素尺寸不匹配,一幅为128x128,另一幅为256x256)。我需要按钮的大小完全相同(否则GUI的不对称性会非常严重)。在不更改实际图像文件的情况下,如何使图像按按钮大小缩放 我尝试创建自己的类,并为button resize事件添加事件处理程序,但这似乎不起作用。我的代码:C# 使用按钮大小制作背景图像比例,c#,winforms,user-interface,C#,Winforms,User Interface,我正在尝试向Win Forms应用程序中的几个按钮添加一些背景图像。这三幅图像大小不同(即像素尺寸不匹配,一幅为128x128,另一幅为256x256)。我需要按钮的大小完全相同(否则GUI的不对称性会非常严重)。在不更改实际图像文件的情况下,如何使图像按按钮大小缩放 我尝试创建自己的类,并为button resize事件添加事件处理程序,但这似乎不起作用。我的代码: class CustomButton : Button { internal void CustomButto
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);
忘记提到,上面的代码根本没有调整图像的大小。按钮仍然需要有不同的大小才能完全显示图像。您可以从以下内容开始
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或其他一些具有更多缩放选项的控件,使用简易编程方式 假设我有一个按钮
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;
}
更好的方法
您可以在custombutton的构造函数中添加eventHandler(只是为了确保正确添加eventHandler)
现在,当您将调整按钮的大小时,您的图像将适合(缩放)到新的大小。将背景图像添加到.NET按钮对象并将其缩放到适合的最简单方法 我使用这种方法来避免对新类和事件处理程序进行任何额外的编码。这也帮助我避免了将所有按钮对象转换为图像对象
BackgroundImage
属性,然后选择导入到项目resources.resx文件中的图像BackgroundImageLayout
属性,然后选择Stretch
确保没有为
图像
和文本
属性输入任何内容,否则它们将干扰新的背景图像。我曾尝试以简洁的方式编写相同的内容,但未能成功。至少请改进代码的外观:)您会认为这样的东西应该已经是.NET Button类的一部分了!这可能有一个缺点,即当按钮被禁用时,图像不会变灰。如果是那样的话,一个医生可能会有所帮助。
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;
}
}