Cómo: Dibujar imágenes con transparencia

Actualización: noviembre 2007

.NET Compact Framework admite la transparencia, pero con un solo color de transparencia. Se debe especificar el mismo color para los intervalos de color alto y bajo en el método SetColorKey(Color, Color).

Ejemplo

En este ejemplo se crea un Bitmap de un rectángulo con diseños rojo y negro, y se muestran dos técnicas para establecer la transparencia:

  • Utilizar el método SetColorKey(Color, Color) basado en un píxel de la imagen. Este ejemplo establece la transparencia mediante el píxel superior izquierdo de la imagen. Dado que este píxel es negro, serán transparentes todos los píxeles que originalmente eran negros.

  • Utilizar el método SetColorKey(Color, Color) con una configuración de colores explícita. Este ejemplo la establece en el color rojo, para que todos los píxeles que originalmente eran rojos sean transparentes.

Para la demostración, en primer lugar ejecute la aplicación con las dos técnicas de transparencia marcadas como comentarios para ver cómo aparece la imagen cuando no hay ninguna transparencia establecida. A continuación quite los comentarios del código correspondiente a cualquiera de las técnicas de transparencia.

' The .NET Compact Framework supports transparency,
' but with only one transparency color.
' The SetColorKey method must have the same color 
' specified for the low color and high color range.

' Note that you must uncomment lines of code
' as indicated for the desired transparency effect.
Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)

' Create a red and black bitmap to demonstrate transparency.
    Dim bmp As New Bitmap(75, 75)
    Dim g As Graphics = Graphics.FromImage(bmp)

    g.FillEllipse(New SolidBrush(Color.Red), 0, 0, bmp.Width, bmp.Width)
    g.DrawLine(New Pen(Color.Black), 0, 0, bmp.Width, bmp.Width)
    g.DrawLine(New Pen(Color.Black), bmp.Width, 0, 0, bmp.Width)
    g.Dispose()


Dim attr As New ImageAttributes

' Set the transparency color key based on the upper-left pixel 
' of the image.
' Uncomment the following line to make all black pixels transparent:
' attr.SetColorKey(bmp.GetPixel(0, 0), bmp.GetPixel(0, 0))

' Set the transparency color key based on a specified value.
' Uncomment the following line to make all red pixels transparent:
' attr.SetColorKey(Color.Red, Color.Red)

' Draw the image using the image attributes.
Dim dstRect As New Rectangle(0, 0, bmp.Width, bmp.Height)
e.Graphics.DrawImage(bmp, dstRect, 0, 0, bmp.Width, bmp.Height, _
    GraphicsUnit.Pixel, attr)

End Sub
// The .NET Compact Framework supports transparency,
// but with only one transparency color.
// The SetColorKey method must have the same color 
// specified for the low color and high color range.

// Note that you must uncomment lines of code
// as indicated for the desired transparency effect.

protected override void OnPaint(PaintEventArgs e)
{
    // Create a red and black bitmap to demonstrate transparency.
    Bitmap bmp = new Bitmap(75,75);
    Graphics g = Graphics.FromImage(bmp);

    g.FillEllipse(new SolidBrush(Color.Red), 0, 0, bmp.Width, bmp.Width);
    g.DrawLine(new Pen(Color.Black), 0, 0, bmp.Width, bmp.Width);
    g.DrawLine(new Pen(Color.Black), bmp.Width, 0, 0, bmp.Width);
    g.Dispose();

    ImageAttributes attr = new ImageAttributes();

    // Set the transparency color key based on the upper-left pixel 
    // of the image.
    // Uncomment the following line to make all black pixels transparent:
    // attr.SetColorKey(bmp.GetPixel(0, 0), bmp.GetPixel(0, 0));

    // Set the transparency color key based on a specified value.
    // Uncomment the following line to make all red pixels transparent:
    // attr.SetColorKey(Color.Red, Color.Red);

    // Draw the image using the image attributes.
    Rectangle dstRect = new Rectangle(0, 0, bmp.Width, bmp.Height);
    e.Graphics.DrawImage(bmp, dstRect, 0, 0, bmp.Width, bmp.Height,
        GraphicsUnit.Pixel, attr);
}

Compilar el código

Para este ejemplo se requieren referencias a los siguientes espacios de nombres:

Programación eficaz

Tenga en cuenta que el objeto Graphics utilizado para crear el mapa de bits se elimina explícitamente. El recolector de elementos no utilizados destruye el objeto Graphics devuelto por la propiedad Graphics del objeto PaintEventArgs, por lo que no es necesario eliminarlo de manera explícita.

Vea también

Otros recursos

Gráficos y dibujos en .NET Compact Framework