Tra*_*vis 6 c# user-interface winforms
我正在尝试将一些背景图像添加到我的Win Forms应用程序中的几个按钮.这三个图像的大小不同(即像素尺寸不匹配,一个是128x128,另一个是256x256).我需要按钮的大小相同(否则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;
}
}
Run Code Online (Sandbox Code Playgroud)
并以形式:
this.buttonOne.Resize += new System.EventHandler(this.buttonOne.CustomButton_Resize);
Run Code Online (Sandbox Code Playgroud)
忘记提及,上面的代码根本没有调整图像的大小.按钮仍需要具有不同的尺寸才能完全显示图像.
gon*_*ins 14
将背景图像添加到.NET Button对象并将其缩放以适应的最简单方法
我使用此方法来避免对新类和事件处理程序进行任何其他编码.这有助于我避免将所有Button对象转换为Image对象.
将图像添加到Resources.resx文件中.
单击您选择的按钮.
导航到该BackgroundImage属性,然后选择导入到项目的resources.resx文件中的图像.
导航到该BackgroundImageLayout属性并选择Stretch.
确保没有为Image和Text属性输入任何内容,否则它们会干扰您的新背景图像.
Sam*_*ami 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;
}
Run Code Online (Sandbox Code Playgroud)
更好的方法
您可以在自定义按钮的构造函数中添加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;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,当您将图像尺寸调整到适合其新尺寸的任何位置时,您将调整按钮的大小.