2014-08-28 164 views
0

我需要在WinForms上繪製透明PNG圖像。我有一個基類:在WinForms上繪製透明圖像

public abstract class BaseSkinable : Panel 
    { 
     protected BaseSkinable() 
     { 
      this.SetStyle(ControlStyles.DoubleBuffer, true); 
      this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); 
      this.SetStyle(ControlStyles.UserPaint, true); 
      this.SetStyle(ControlStyles.ResizeRedraw, true); 
     } 

    protected abstract void OnDraw(Graphics graphics); 


    protected override CreateParams CreateParams 
    { 
     get 
     { 
      CreateParams cp = base.CreateParams; 
      cp.ExStyle |= 0x00000020; 
      return cp; 
     } 
    } 

    protected override void OnPaintBackground(PaintEventArgs e) { } 

    protected override void OnPaint(PaintEventArgs e) 
    { 

     e.Graphics.TextRenderingHint = 
      System.Drawing.Text.TextRenderingHint.AntiAlias; 
     e.Graphics.InterpolationMode = 
      System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; 
     e.Graphics.PixelOffsetMode = 
      System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; 
     e.Graphics.SmoothingMode = 
      System.Drawing.Drawing2D.SmoothingMode.HighQuality; 

     OnDraw(e.Graphics); 
    } 
} 

在繼承的類:

protected override void OnDraw(Graphics graphics) 
    { 

     Image toDraw = SelectImageToDraw(); 

     if (toDraw == null) 
     { 
      NoImageDraw(graphics); 
      return; 
     } 

     int width = toDraw.Size.Width; 
     int height = toDraw.Size.Height; 
     Rectangle rect = new Rectangle(0, 0, width, height); 

     graphics.DrawImage(toDraw, rect); 
    } 

我需要重畫的圖像,如果用戶移動鼠標移到控制。但問題是反對繪製覆蓋舊圖像。就像我們畫圖層一樣。 Winforms可能不清晰圖形和我的方法吸引了過去的圖片。如何解決它,可能我做錯了什麼。

+0

所以,你想繪製一個PNG圖像到你的面板控制? – 2014-08-28 20:17:42

+0

我有一個透明的PNG圖像。我需要製作一個「ImageButton」 - 控制鼠標進入,離開和點擊時重繪圖像的方式。所以問題是這個ImageButton需要透明且沒有邊框。 – user2598575 2014-08-30 05:54:06

+0

你想在一個按鈕上繪製一個透明的圖像。按鈕後面是「表格」? 「形式」也是不透明的? – 2014-08-30 08:38:09

回答

1

很難理解你的問題是什麼 - 但你想在繪製東西之前清除背景嗎?

使用Graphics對象,您可以使用背景顏色調用Clear。如果它背後有另一個圖像,我可以看到你的一些挫折 - 但我認爲你只需要設置一個透明的顏色(並提供Clear方法的透明顏色)。在我看來,應該清理一切。

http://msdn.microsoft.com/en-us/library/system.drawing.graphics.clear%28v=vs.110%29.aspx

希望幫助或回答你希望得到回答的問題。

+0

調用Clear()我需要使用Color作爲參數,但我不能使用它,因爲我不會填充背景。 Color.Transparent無法正常工作 – user2598575 2014-08-28 18:59:48

+0

您是否在控件上設置了ColorKey,並且可以使用該Color? – Locke 2014-08-28 19:43:12