使用組合模式控制阿爾法混合
有時候您可能會想要建立具有下列特性的螢幕外點陣圖:
- 色彩具有小於 255 的 Alpha 值。
- 當您建立位圖時,色彩不會進行 alpha 混合。
- 當您顯示完成的點陣圖時,點陣圖中的色彩會與顯示裝置上的背景色彩混合。
若要建立這類位圖,請建構空白 Bitmap 對象,然後根據該位圖建構 Graphics 物件。 將 Graphics 物件的撰寫模式設定為 CompositingModeSourceCopy。
下列範例會根據 Bitmap 物件,建立 Graphics 物件。 程式碼使用 Graphics 物件及兩個半透明筆刷(alpha = 160)在位圖上繪畫。 程序代碼會使用半透明筆刷填滿紅色橢圓形和綠色橢圓形。 綠色橢圓形與紅色橢圓形重疊,但綠色不會與紅色混合,因為 Graphics 對象的組合模式會設定為 CompositingModeSourceCopy。
接下來,程式代碼會根據裝置內容呼叫 BeginPaint 並建立 Graphics 物件,以準備在畫面上繪製。 程序代碼會在畫面上繪製位圖兩次:一次位於白色背景,一次在多色背景上。 位圖中屬於兩個橢圓形的像素具有 160 的 alpha 通道,因此這些橢圓形將會混合到螢幕上的背景色彩中。
// Create a blank bitmap.
Bitmap bitmap(180, 100);
// Create a Graphics object that can be used to draw on the bitmap.
Graphics bitmapGraphics(&bitmap);
// Create a red brush and a green brush, each with an alpha value of 160.
SolidBrush redBrush(Color(210, 255, 0, 0));
SolidBrush greenBrush(Color(210, 0, 255, 0));
// Set the compositing mode so that when overlapping ellipses are drawn,
// the colors of the ellipses are not blended.
bitmapGraphics.SetCompositingMode(CompositingModeSourceCopy);
// Fill an ellipse using a red brush that has an alpha value of 160.
bitmapGraphics.FillEllipse(&redBrush, 0, 0, 150, 70);
// Fill a second ellipse using green brush that has an alpha value of 160.
// The green ellipse overlaps the red ellipse, but the green is not
// blended with the red.
bitmapGraphics.FillEllipse(&greenBrush, 30, 30, 150, 70);
// Prepare to draw on the screen.
hdc = BeginPaint(hWnd, &ps);
Graphics* pGraphics = new Graphics(hdc);
pGraphics->SetCompositingQuality(CompositingQualityGammaCorrected);
// Draw a multicolored background.
SolidBrush brush(Color((ARGB)Color::Aqua));
pGraphics->FillRectangle(&brush, 200, 0, 60, 100);
brush.SetColor(Color((ARGB)Color::Yellow));
pGraphics->FillRectangle(&brush, 260, 0, 60, 100);
brush.SetColor(Color((ARGB)Color::Fuchsia));
pGraphics->FillRectangle(&brush, 320, 0, 60, 100);
// Display the bitmap on a white background.
pGraphics->DrawImage(&bitmap, 0, 0);
// Display the bitmap on a multicolored background.
pGraphics->DrawImage(&bitmap, 200, 0);
delete pGraphics;
EndPaint(hWnd, &ps);
下圖顯示上述程式代碼的輸出。 請注意,省略號會與背景融合,但它們彼此之間並不融合。
顯示兩個不同色彩橢圓形的插圖
上述程式代碼範例具有下列 語句:
bitmapGraphics.SetCompositingMode(CompositingModeSourceCopy);
如果您想要將省略號與彼此以及背景混合,請將該語句變更為下列內容:
bitmapGraphics.SetCompositingMode(CompositingModeSourceOver);
下圖顯示修訂程式碼的輸出。
使用組合模式控制 Alpha 混合圖例