Como: Use uma matriz de cores para definir valores de alfa em imagens

O Bitmap classe (que herda a Image classe) e o ImageAttributes classe fornecem funcionalidade para obter e definir valores de pixel. Você pode usar o ImageAttributes valores de classe para modificar a alfa para uma imagem inteira, ou você pode chamar o SetPixel método o Bitmap classe para modificar valores de pixel individual.

Exemplo

O ImageAttributes classe tem várias propriedades que você pode usar para modificar imagens durante o processamento. No exemplo a seguir, um ImageAttributes objeto é usado para definir todos os valores alfa 80% dos quais eles foram. Isso é feito ao inicializar uma matriz de cores e definir a escala do valor na matriz para 0,8 de alfa. O endereço da matriz de cores é passado para o SetColorMatrix método da ImageAttributes objeto e o ImageAttributes objeto é passado para o DrawString método o Graphics objeto.

Durante o processamento, os valores alfa no bitmap são convertidos para 80% dos quais eles foram. Isso resulta em uma imagem que é combinada com o plano de fundo. Como mostra a ilustração a seguir, a imagem de bitmap parece transparente; Você pode ver a linha preta sólida através dele.

Combinação alfa usando uma matriz

Onde a imagem é sobre a parte branca do plano de fundo, a imagem tem sido combinada com a cor branca. Onde a imagem cruza a linha preta, a imagem é combinada com o cores preto.

        ' Create the Bitmap object and load it with the texture image.
        Dim bitmap As New Bitmap("Texture.jpg")

        ' Initialize the color matrix.
        ' Note the value 0.8 in row 4, column 4.
        Dim matrixItems As Single()() = { _
           New Single() {1, 0, 0, 0, 0}, _
           New Single() {0, 1, 0, 0, 0}, _
           New Single() {0, 0, 1, 0, 0}, _
           New Single() {0, 0, 0, 0.8F, 0}, _
           New Single() {0, 0, 0, 0, 1}}

        Dim colorMatrix As New ColorMatrix(matrixItems)

        ' Create an ImageAttributes object and set its color matrix.
        Dim imageAtt As New ImageAttributes()
        imageAtt.SetColorMatrix( _
           colorMatrix, _
           ColorMatrixFlag.Default, _
           ColorAdjustType.Bitmap)

        ' First draw a wide black line.
        e.Graphics.DrawLine( _
           New Pen(Color.Black, 25), _
           New Point(10, 35), _
           New Point(200, 35))

        ' Now draw the semitransparent bitmap image.
        Dim iWidth As Integer = bitmap.Width
        Dim iHeight As Integer = bitmap.Height

        ' Pass in the destination rectangle (2nd argument) and the x _
        ' coordinate (3rd argument), x coordinate (4th argument), width _
        ' (5th argument), and height (6th argument) of the source rectangle.
        e.Graphics.DrawImage( _
           bitmap, _
           New Rectangle(30, 0, iWidth, iHeight), _
           0.0F, _
           0.0F, _
           iWidth, _
           iHeight, _
           GraphicsUnit.Pixel, _
           imageAtt)

// Create the Bitmap object and load it with the texture image.
Bitmap bitmap = new Bitmap("Texture.jpg");

// Initialize the color matrix.
// Note the value 0.8 in row 4, column 4.
float[][] matrixItems ={ 
   new float[] {1, 0, 0, 0, 0},
   new float[] {0, 1, 0, 0, 0},
   new float[] {0, 0, 1, 0, 0},
   new float[] {0, 0, 0, 0.8f, 0}, 
   new float[] {0, 0, 0, 0, 1}};
ColorMatrix colorMatrix = new ColorMatrix(matrixItems);

// Create an ImageAttributes object and set its color matrix.
ImageAttributes imageAtt = new ImageAttributes();
imageAtt.SetColorMatrix(
   colorMatrix,
   ColorMatrixFlag.Default,
   ColorAdjustType.Bitmap);

// First draw a wide black line.
e.Graphics.DrawLine(
   new Pen(Color.Black, 25),
   new Point(10, 35),
   new Point(200, 35));

// Now draw the semitransparent bitmap image.
int iWidth = bitmap.Width;
int iHeight = bitmap.Height;
e.Graphics.DrawImage(
   bitmap,
   new Rectangle(30, 0, iWidth, iHeight),  // destination rectangle
   0.0f,                          // source rectangle x 
   0.0f,                          // source rectangle y
   iWidth,                        // source rectangle width
   iHeight,                       // source rectangle height
   GraphicsUnit.Pixel,
   imageAtt);

Compilando o código

O exemplo anterior é projetado para uso com o Windows Forms e requer PaintEventArgs e, que é um parâmetro de PaintEventHandler.

Consulte também

Outros recursos

Elementos gráficos e desenho em formulários do Windows

Preenchimentos e linhas de mistura alfa