次の方法で共有


カラー マトリックスを使用して画像のアルファ値を設定する

Bitmap クラス (Image クラスから継承) と ImageAttributes クラスは、ピクセル値を取得および設定するための機能を提供します。 ImageAttributes クラスを使用してイメージ全体のアルファ値を変更したり、Bitmap クラスの Bitmap::SetPixel メソッドを呼び出して個々のピクセル値を変更したりできます。 個々のピクセル値の設定の詳細については、「個々のピクセルのアルファ値を設定する」を参照してください。

次の例では、広い黒い線を描画し、その線の一部を覆う不透明なイメージを表示します。

Bitmap bitmap(L"Texture1.jpg");
Pen pen(Color(255, 0, 0, 0), 25);
// First draw a wide black line.
graphics.DrawLine(&pen, Point(10, 35), Point(200, 35));
// Now draw an image that covers part of the black line.
graphics.DrawImage(&bitmap,
   Rect(30, 0, bitmap.GetWidth(), bitmap.GetHeight()));

次の図は、(30, 0) で描画される結果の画像を示しています。 広い黒い線が画像を通して表示されない点に注意してください。

薄く広い黒い四角形を重ね合わせた不透明な画像を示す図

ImageAttributes クラスには、レンダリング中にイメージを変更するために使用できる多くのプロパティがあります。 次の例では、ImageAttributes オブジェクトを使用して、すべてのアルファ値を 80% に設定しています。 これを行うには、カラー マトリックスを初期化し、マトリックス内のアルファ スケーリング値を 0.8 に設定します。 カラー マトリックスのアドレスは、ImageAttributes オブジェクトの ImageAttributes::SetColorMatrix メソッドに渡され、ImageAttributes オブジェクトのアドレスは、Graphics オブジェクトの DrawImage メソッドに渡されます。

// Create a Bitmap object and load it with the texture image.
Bitmap bitmap(L"Texture1.jpg");
Pen pen(Color(255, 0, 0, 0), 25);
// Initialize the color matrix.
// Notice the value 0.8 in row 4, column 4.
ColorMatrix colorMatrix = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
                           0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
                           0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
                           0.0f, 0.0f, 0.0f, 0.8f, 0.0f,
                           0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
// Create an ImageAttributes object and set its color matrix.
ImageAttributes imageAtt;
imageAtt.SetColorMatrix(&colorMatrix, ColorMatrixFlagsDefault,
   ColorAdjustTypeBitmap);
// First draw a wide black line.
graphics.DrawLine(&pen, Point(10, 35), Point(200, 35));
// Now draw the semitransparent bitmap image.
INT iWidth = bitmap.GetWidth();
INT iHeight = bitmap.GetHeight();
graphics.DrawImage(
   &bitmap, 
   Rect(30, 0, iWidth, iHeight),  // Destination rectangle
   0,                             // Source rectangle X 
   0,                             // Source rectangle Y
   iWidth,                        // Source rectangle width
   iHeight,                       // Source rectangle height
   UnitPixel, 
   &imageAtt);

レンダリング中、ビットマップ内のアルファ値は、元の値の 80% に変換されます。 これにより、背景とブレンドされたイメージが作成されます。 次の図に示すように、ビットマップイメージは透明に見えます。あなたはそれを通して黒い実線を見ることができます。

前の図に似ていますが、画像は半透明です

画像が背景の白い部分の上にある場合、画像は白の色とブレンドされています。 イメージが黒い線を越える場合、イメージは黒の色とブレンドされます。