2007年的時候,Alex在《Compelling UI's in NetCF anybody?》一文中,講述了windows mobile 5平台上如何利用AlphaBlend做很酷的透明圖片介面。前不久的webcast《24 Hours of Windows Mobile Application Development: Creating Compelling and Attractive UIs for Windows Mobile Applications》上,他講述了目前windows mobile介面設計的趨勢,其中也涉及到了Alpha Blending 和 Alpha Channel技術。下面對這兩個概念進行解釋。
在百科全書wiki上,我們可以找到這個Alpha compositing的解釋。在電腦圖形學中,alpha compositing是一種結合圖片和背景來創造部分透明效果的技術。Alpha Channel最早是由A. R. Smith在20世紀70年代提出來,最終由Thomas Porter和Tom Duff在1984年發展成熟。簡單來說,傳統的一個像素的顏色是用RGB來表示的,而在Alpha Channel中,需要加上第四個參數,如(0.0, 0.5, 0.0, 0.5)中,前面的三個參數“0.0, 0.5, 0.0”表示RGB,而第四個參數0.5表示Alpha值。因此,在Thomas Porter和Tom Duff的論文中,他們利用Alpha值,定義了兩張圖片合成的5種運算(over,in,out,atop,xor),效果可以參考1:
圖1:5種運算(圖片摘自Alpha compositing)
目前,支援Alpha Blending的作業系統/GUI包括以下幾種:
- Mac OS X
- Windows 2000, XP, Server 2003, Windows CE, Vista and Windows 7
- The XRender extension to the X Window System (this includes modern Linux systems)
- RISC OS Adjust
- QNX Neutrino
- Plan 9
- Inferno
- AmigaOS 4.1
- BeOS, Zeta and Haiku
- Syllable
- MorphOS
從windows mobile 5.0開始,平台就已經支援Alpha Blending的本地調用了。在http://code.msdn.microsoft.com/uiframework這個課程代碼中,我們可以看到,在工程中,他採用了P/Invoke:
Code
[DllImport("coredll.dll")]
extern public static Int32 AlphaBlend(IntPtr hdcDest, Int32 xDest, Int32 yDest, Int32 cxDest, Int32 cyDest, IntPtr hdcSrc, Int32 xSrc, Int32 ySrc, Int32 cxSrc, Int32 cySrc, BlendFunction blendFunction);
封裝了DrawAlpha這個方法:
Code
public static void DrawAlpha(this Graphics gx, Bitmap image, byte transparency, int x, int y)
{
using (Graphics gxSrc = Graphics.FromImage(image))
{
IntPtr hdcDst = gx.GetHdc();
IntPtr hdcSrc = gxSrc.GetHdc();
BlendFunction blendFunction = new BlendFunction();
blendFunction.BlendOp = (byte)BlendOperation.AC_SRC_OVER; // Only supported blend operation
blendFunction.BlendFlags = (byte)BlendFlags.Zero; // Documentation says put 0 here
blendFunction.SourceConstantAlpha = transparency; // Constant alpha factor
blendFunction.AlphaFormat = (byte)0; // Don't look for per pixel alpha
PlatformAPIs.AlphaBlend(hdcDst, x, y, image.Width, image.Height,
hdcSrc, 0, 0, image.Width, image.Height, blendFunction);
gx.ReleaseHdc(hdcDst); // Required cleanup to GetHdc()
gxSrc.ReleaseHdc(hdcSrc); // Required cleanup to GetHdc()
}
}
最後,作者給出了這個方法的應用,在案頭上顯示天氣的UI和圖片的Slide Show。同時,可以使用下面的代碼來隱藏title bar,並全螢幕顯示應用程式。
Code
// Don't show title bar and allocate the full screen
this.FormBorderStyle = FormBorderStyle.None;
this.WindowState = FormWindowState.Maximized;
另外,作者還給出了按鈕浮起和按下狀態的顏色變化處理,以及text文本嵌入的處理,大家有需要的話,可以下載過來參考一下。
最終的顯示效果如2所示:
圖2:程式UI效果
是Location平常狀態與被按下時的對比:
圖3:按鈕的不同效果
參考連結:
Alex:Compelling UI's in NetCF anybody?》
MSDN:AlphaBlend
Webcast:24 Hours of Windows Mobile Application Development: Creating Compelling and Attractive UIs for Windows Mobile Applications》
Wiki:Alpha compositing