2009-04-23 86 views
1

我有一個圖像(PNG文件)具有設置爲50%不透明的alpha通道。當我嘗試在TransparencyKey設置爲白色並且背景顏色設置爲白色的表單上繪製圖像時,我希望圖像被繪製爲50%透視。但是,它首先與背景顏色混合,因此它完全不透明。有沒有辦法解決?我不想設置窗體的不透明屬性,因爲窗體上的某些圖像需要半透明,有些圖像需要不透明。透明Winform與圖像

回答

0

我不認爲你可以。我們有一個啓動畫面,我們做了這樣的事情,但我們最終捕獲了屏幕並將其設置爲表單的背景圖像。顯然,這似乎只有工作,如果屏幕更改,表單的背景不會,而且事情看起來很奇怪。如果你找到了更好的方法,我很想知道它。

這裏是捕捉屏幕的代碼,只需設置ScreenRect的形式屏幕座標和呼叫處理():

using System; 
using System.Drawing; 
using System.Runtime.InteropServices; 

namespace TourFactory.Core.Drawing 
{ 
    public class CaptureScreenCommand 
    { 

     #region Initialization and Destruction 

     public CaptureScreenCommand() 
     { 
     } 

     #endregion 

     #region Fields and Properties 

     // BitBlt is a multipurpose function that takes a ROP (Raster OPeration) code 
     // that controls exactly what it does. 0xCC0020 is the ROP code SRCCOPY, i.e. 
     // do a simple copy from the source to the destination. 
     private const int cRasterOp_SrcCopy = 0xCC0020; // 13369376; 

     private Rectangle mScreenRect; 
     /// <summary> 
     /// Gets or sets the screen coordinates to capture. 
     /// </summary> 
     public Rectangle ScreenRect 
     { 
      get { return mScreenRect; } 
      set { mScreenRect = value; } 
     } 

     #endregion 

     #region Methods 

     public Image Process() 
     { 
      // use the GDI call and create a DC to the whole display 
      var dc1 = CreateDC("DISPLAY", null, 0, 0); 
      var g1 = Graphics.FromHdc(dc1); 

      // create a compatible bitmap the size of the form 
      var bmp = new Bitmap(mScreenRect.Width, mScreenRect.Height, g1); 
      var g2 = Graphics.FromImage(bmp); 

      // Now go retrace our steps and get the device contexts for both the bitmap and the screen 
      // Note: Apparently you have to do this, and can't go directly from the aquired dc or exceptions are thrown 
      // when you try to release the dcs 
      dc1 = g1.GetHdc(); 
      var dc2 = g2.GetHdc(); 

      // Bit Blast the screen into the Bitmap 
      BitBlt(dc2, 0, 0, mScreenRect.Width, mScreenRect.Height, dc1, mScreenRect.Left, mScreenRect.Top, cRasterOp_SrcCopy); 

      // Remember to release the dc's, otherwise problems down the road 
      g1.ReleaseHdc(dc1); 
      g2.ReleaseHdc(dc2); 

      // return bitmap 
      return bmp; 
     } 

     #endregion 

     #region gdi32.dll 

     [DllImport("gdi32")] 
     private static extern IntPtr CreateDC(string lpDriverName, string lpDeviceName, int lpOutput, int lpInitData); 

     [DllImport("gdi32")] 
     private static extern bool BitBlt(IntPtr hdcDest, int xDest, int yDest, int width, int height, IntPtr hdcSrc, int xSrc, int ySrc, int dwRop); 

     #endregion 

    } 
}