Compartir a través de


Cómo: Utilizar una matriz de colores para establecer valores alfa en imágenes

La clase Bitmap (que se hereda de la clase Image) y la clase ImageAttributes proporcionan funcionalidad para obtener y establecer valores de píxeles. La clase ImageAttributes puede utilizarse para modificar los valores alfa de toda una imagen o se puede llamar al método SetPixel de la clase Bitmap para modificar valores de píxeles individuales.

Ejemplo

La clase ImageAttributes tiene muchas propiedades que se pueden utilizar para modificar las imágenes durante la representación. En el ejemplo siguiente se utiliza un objeto ImageAttributes para establecer todos los valores alfa en el 80 por ciento de lo que eran anteriormente. Esto se hace inicializando una matriz de colores y estableciendo el valor de escala alfa de la matriz en 0.8. La dirección de la matriz de colores se pasa al método SetColorMatrix del objeto ImageAttributes y el objeto ImageAttributes se pasa al método DrawString del objeto Graphics.

Durante la representación, los valores alfa del mapa de bits se convierten al 80 por ciento de lo que eran anteriormente. Esto produce una imagen que se mezcla con el fondo. Tal como muestra la imagen siguiente, la imagen del mapa de bits aparece transparente y la línea negra sólida se puede ver a través de ella.

Combinación alfa usando una matriz

En el lugar donde la imagen está sobre la parte blanca del fondo, la imagen se ha mezclado con el color blanco. En el lugar donde la imagen cruza la línea negra, la imagen se mezcla con el color negro.

        ' 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);

Compilar el código

El ejemplo anterior está diseñado para formularios Windows Forms y requiere PaintEventArgs e, que es un parámetro de PaintEventHandler.

Vea también

Otros recursos

Gráficos y dibujos en Windows Forms

Líneas y rellenos con mezcla alfa