Iphone之所以那麼流行一部分歸功於他的炫麗的介面,其實那些介面的實現主要由兩大功能組成:畫透明圖片和畫漸層效果。這次主要講述windows mobile下畫透明圖片。
所謂透明圖片其實就是把圖片背景設定成透明,如果直接畫出圖片會顯示一個規則正方形的圖,其中圖片包括不規則圖形和該映像下的背景,所以如果只是想畫出不規則圖形,需要把背景去掉。下面為去掉背景的實現。
/// <summary>
/// Draws the image with transparency
/// </summary>
/// <param name="gx">Destination graphics</param>
/// <param name="image">The image to draw</param>
/// <param name="destRect">Desctination rectangle</param>
public static void DrawImageTransparent(this Graphics gx, Image image, Rectangle destRect)
{
ImageAttributes imageAttr = new ImageAttributes();
Color transpColor = GetTransparentColor(image);
imageAttr.SetColorKey(transpColor, transpColor);
gx.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, imageAttr);
imageAttr.Dispose();
}
private static Color GetTransparentColor(Image image)
{
return ((Bitmap)image).GetPixel(image.Width - 1, image.Height - 1);
}
先調用Bitmap.GetPixel()函數取出圖片的背景資訊,然後設定ImageAttributes 的屬性,在畫圖的時候把圖片屬性傳遞到Graphics.DrawImage()函數進行繪畫。
如下:
有些圖片做的不好,有點鋸齒。
下面是沒有去掉背景的圖片,作為比較。