2011-12-09 45 views
2

我正在研究ImageButton,在该按钮中绘制了此按钮的每个状态(每个状态都有多个图像)(如mouseOver,mouseDown等)。透明用户控件的清晰背景

我已经使用这个代码所做的控制透明:

public ImageButton() 
{ 
    InitializeComponent(); 

    this.SetStyle(ControlStyles.Opaque, true); 
    this.SetStyle(ControlStyles.OptimizedDoubleBuffer, false); 
} 

protected override CreateParams CreateParams 
{ 
    get 
    { 
     CreateParams parms = base.CreateParams; 
     parms.ExStyle |= 0x20; 
     return parms; 
    } 
} 

但是有一个问题,国家的几个开关后,边角变得尖锐和丑陋的,为了解决这个问题,我需要明确的背景下,但如果我的控制是透明的,那么这是不可能的。

我试过这个解决方案:Clearing the graphics of a transparent panel C# 但它很慢,使控制闪烁。

你有什么想法如何清除此背景并保持透明度控制?

+0

你需要什么样的透明度?只是通过显示的父级背景?或者你想要其他控件和/或其他窗口的透明度? –

回答

1

好的,我已经解决了这个问题。 我已经解决了它的设置控制不透明,我画我的控制下的画布,作为我的ImageButton的背景。

溶液(在画图事件):

//gets position of button and transforms it to point on whole screen 
//(because in next step we'll get screenshot of whole window [with borders etc]) 
Point btnpos = this.Parent.PointToScreen(new Point(Location.X, Location.Y)); 

//now our point will be relative to the edges of form 
//[including borders, which we'll have on our bitmap] 
if (this.Parent is Form) 
{ 
     btnpos.X -= this.Parent.Left; 
     btnpos.Y -= this.Parent.Top; 
} 
else 
{ 
    btnpos.X = this.Left; 
    btnpos.Y = this.Top; 
} 

//gets screenshot of whole form 
Bitmap b = new Bitmap(this.Parent.Width, this.Parent.Height); 
this.Parent.DrawToBitmap(b, new Rectangle(new Point(0, 0), this.Parent.Size)); 

//draws background (which simulates transparency) 
e.Graphics.DrawImage(b, 
       new Rectangle(new Point(0, 0), this.Size), 
       new Rectangle(btnpos, this.Size), 
       GraphicsUnit.Pixel); 

//do whatever you want to draw your stuff 

PS。它在设计时不起作用。

+0

我注意到另一个问题。当按钮处于清除状态时(例如不在PictureBox上),则位图将包含他绘制的内容,并且不能正常工作。如何重新绘制背景,然后我的控制(有没有我的控制位图)? –