使用按钮大小制作背景图像比例 [英] Making a background image scale with button size

查看:36
本文介绍了使用按钮大小制作背景图像比例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to add some background images to a few buttons in my Win Forms application. The three images are different sizes (ie pixel dimensions don't match, one is 128x128 and another is 256x256). I need the buttons to be identical in size (otherwise the GUI is horribly asymmetrical). Without changing the actual image files, how can I get the images to scale with button size?

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

I've tried creating my own class, and adding an event handler for the button resize event, but that doesn't seem to work. My code:

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

忘了说,上面的代码根本没有调整图像大小.按钮仍然需要有不同的大小才能完整显示图像.

Forgot to mention, the above code does not resize the images at all. The buttons still need to have different sizes to display the images completely.

推荐答案

简单的程序化方式

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

Say I have a button btn1, Following code is working perfectly in 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)

You can add eventHandler in the constructor of your custombutton (just to ensure that you are adding eventhandler correctly)

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

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

Now when you will resize the button anywhere your image will get fit(scaled) to its new size.

这篇关于使用按钮大小制作背景图像比例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆