2011-12-09 53 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上),則位圖將包含他繪製的內容,並且不能正常工作。如何重新繪製背景,然後我的控制(有沒有我的控制位圖)? –