大家在重写控件的BackgroundImage不知道有没有发现一个问题(由于BackgroundImage只能显示图像的实际大小,不能进行拉伸或压缩,因此重写BackgroundImage属性)这个时候,我发现了一些问题(前提是所要显示的图像大小与BackgroundImage的显示区域大小不一样)
如下:
定义变量
private System.Drawing.Image backgroundImage = null;
重写BackgroundImage
public override Image BackgroundImage
{
get
{
return this.backgroundImage;
}
set
{
this.backgroundImage = value;
if ( this.backgroundImage == null ) base.BackgroundImage = null;
else
{
if ( this.Width != 0 && this.Height != 0 )
{
System.Drawing.Image backimage = new System.Drawing.Bitmap( this.Width , this.Height );
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage( backimage );
g.DrawImage( this.backgroundImage , new System.Drawing.Rectangle( new System.Drawing.Point( 0 , 0 ) , this.Size ) );
base.BackgroundImage = backimage;
} }
}
}
这个时候,如果所要显示的图像大小与BackgroundImage的显示区域大小不一样则所要显示的图像不能被拉伸或压缩,而如果将重写(override)变为隐藏(new),则显示的图像就可以被拉伸或压缩。这是为什么?

解决方案 »

  1.   

    else
    {
    if ( this.Width != 0 && this.Height != 0 )
    {
    System.Drawing.Image backimage = new System.Drawing.Bitmap( this.Width , this.Height );
    System.Drawing.Graphics g = System.Drawing.Graphics.FromImage( backimage );
    g.DrawImage( this.backgroundImage , new System.Drawing.Rectangle( new System.Drawing.Point( 0 , 0 ) , this.Size ) );
    base.BackgroundImage = backimage;

    你这里太聪明了,直接赋值就可以,你还自作聪明的自己缩放了一下,这些系统会自己做,不要劳繁你动手,
    关键就是,你自己缩放就好了,但是不做彻底一点,
    backgroundImage = backimage; //加上这一句就一致了
      

  2.   

    Jimh,我认为你的回答不正确。
    首先,我之所以没有直接赋值,是因为我的程序里这是一个方法的调用,为了上传方便我经过了整理,所以没有去掉赋值;
    其次,控件背景是不会自己拉伸或缩放的,这一部份的工作必须于自己来完成;
    最后,你的backgroundImage = backimage;我不太清楚是什么意思?根据你的说法,我进行了几种我认为的修改,但是没有任何的效果。
      

  3.   

    不要用this.Width和this.Height这两个控件属性,要用ClientSize这个控件来做显示尺寸大小。