Procedimiento para crear un degradado de trazado

La clase PathGradientBrush permite personalizar la forma de rellenar una forma con colores que cambian gradualmente. Por ejemplo, puede especificar un color para el centro de un trazado y otro color para el límite de un trazado. También puede especificar colores independientes para varios puntos a lo largo del límite de un trazado.

Nota

En GDI+, un trazado es una secuencia de líneas y curvas mantenidas mediante un objeto GraphicsPath. Para obtener más información sobre los trazados de GDI+, vea Trazados de gráficos en GDI+ y Creación y dibujo de trazados.

Los ejemplos de este artículo son métodos a los que se llama desde el controlador de eventos Paint de un control.

Para rellenar una elipse con un degradado de trazado

  • En el ejemplo siguiente se rellena una elipse con un pincel de degradado de trazado. El color central se establece en azul y el color del límite, en aguamarina. En la siguiente ilustración se muestra la elipse rellenada.

    Trazado degradado que rellena una elipse.

    De forma predeterminada, un pincel de degradado de trazado no se extiende fuera del límite del trazado. Si usa el pincel de degradado de trazado para rellenar una figura que se extiende más allá del límite del trazado, el área de la pantalla situada fuera del trazado no se rellenará.

    En la ilustración siguiente se muestra lo que sucede si se cambia la llamada a Graphics.FillEllipse en el código siguiente a e.Graphics.FillRectangle(pthGrBrush, 0, 10, 200, 40):

    Trazado de degradado extendido por encima de sus límites.

    public void FillEllipseWithPathGradient(PaintEventArgs e)
    {
        // Create a path that consists of a single ellipse.
        GraphicsPath path = new GraphicsPath();
        path.AddEllipse(0, 0, 140, 70);
    
        // Use the path to construct a brush.
        PathGradientBrush pthGrBrush = new PathGradientBrush(path);
    
        // Set the color at the center of the path to blue.
        pthGrBrush.CenterColor = Color.FromArgb(255, 0, 0, 255);
    
        // Set the color along the entire boundary
        // of the path to aqua.
        Color[] colors = { Color.FromArgb(255, 0, 255, 255) };
        pthGrBrush.SurroundColors = colors;
    
        e.Graphics.FillEllipse(pthGrBrush, 0, 0, 140, 70);
    }
    
    ' Create a path that consists of a single ellipse.
    Dim path As New GraphicsPath()
    path.AddEllipse(0, 0, 140, 70)
    
    ' Use the path to construct a brush.
    Dim pthGrBrush As New PathGradientBrush(path)
    
    ' Set the color at the center of the path to blue.
    pthGrBrush.CenterColor = Color.FromArgb(255, 0, 0, 255)
    
    ' Set the color along the entire boundary 
    ' of the path to aqua.
    Dim colors As Color() = {Color.FromArgb(255, 0, 255, 255)}
    pthGrBrush.SurroundColors = colors
    
    e.Graphics.FillEllipse(pthGrBrush, 0, 0, 140, 70)
    
    

    El ejemplo de código anterior está diseñado para su uso con Windows Forms y requiere PaintEventArgs, que es un parámetro de PaintEventHandler.

Para especificar puntos en el límite

  • En el ejemplo siguiente se construye un pincel de degradado de trazado a partir de un trazado con forma de estrella. El código establece la propiedad CenterColor, que establece en rojo el color del centroide de la estrella. A continuación, el código establece la propiedad SurroundColors para especificar varios colores (almacenados en la matriz colors) en los puntos individuales de la matriz points. La instrucción de código final rellena el trazado con forma de estrella con el pincel de degradado de trazado.

    public void ConstructBrushFromStarShapedPath(PaintEventArgs e)
    {
        // Put the points of a polygon in an array.
        Point[] points = {
           new Point(75, 0),
           new Point(100, 50),
           new Point(150, 50),
           new Point(112, 75),
           new Point(150, 150),
           new Point(75, 100),
           new Point(0, 150),
           new Point(37, 75),
           new Point(0, 50),
           new Point(50, 50)};
    
        // Use the array of points to construct a path.
        GraphicsPath path = new GraphicsPath();
        path.AddLines(points);
    
        // Use the path to construct a path gradient brush.
        PathGradientBrush pthGrBrush = new PathGradientBrush(path);
    
        // Set the color at the center of the path to red.
        pthGrBrush.CenterColor = Color.FromArgb(255, 255, 0, 0);
    
        // Set the colors of the points in the array.
        Color[] colors = {
           Color.FromArgb(255, 0, 0, 0),
           Color.FromArgb(255, 0, 255, 0),
           Color.FromArgb(255, 0, 0, 255),
           Color.FromArgb(255, 255, 255, 255),
           Color.FromArgb(255, 0, 0, 0),
           Color.FromArgb(255, 0, 255, 0),
           Color.FromArgb(255, 0, 0, 255),
           Color.FromArgb(255, 255, 255, 255),
           Color.FromArgb(255, 0, 0, 0),
           Color.FromArgb(255, 0, 255, 0)};
    
        pthGrBrush.SurroundColors = colors;
    
        // Fill the path with the path gradient brush.
        e.Graphics.FillPath(pthGrBrush, path);
    }
    
    ' Put the points of a polygon in an array.
    Dim points As Point() = { _
       New Point(75, 0), _
       New Point(100, 50), _
       New Point(150, 50), _
       New Point(112, 75), _
       New Point(150, 150), _
       New Point(75, 100), _
       New Point(0, 150), _
       New Point(37, 75), _
       New Point(0, 50), _
       New Point(50, 50)}
    
    ' Use the array of points to construct a path.
    Dim path As New GraphicsPath()
    path.AddLines(points)
    
    ' Use the path to construct a path gradient brush.
    Dim pthGrBrush As New PathGradientBrush(path)
    
    ' Set the color at the center of the path to red.
    pthGrBrush.CenterColor = Color.FromArgb(255, 255, 0, 0)
    
    ' Set the colors of the points in the array.
    Dim colors As Color() = { _
       Color.FromArgb(255, 0, 0, 0), _
       Color.FromArgb(255, 0, 255, 0), _
       Color.FromArgb(255, 0, 0, 255), _
       Color.FromArgb(255, 255, 255, 255), _
       Color.FromArgb(255, 0, 0, 0), _
       Color.FromArgb(255, 0, 255, 0), _
       Color.FromArgb(255, 0, 0, 255), _
       Color.FromArgb(255, 255, 255, 255), _
       Color.FromArgb(255, 0, 0, 0), _
       Color.FromArgb(255, 0, 255, 0)}
    
    pthGrBrush.SurroundColors = colors
    
    ' Fill the path with the path gradient brush.
    e.Graphics.FillPath(pthGrBrush, path)
    
  • En el ejemplo siguiente se dibuja un degradado de trazado sin un objeto GraphicsPath en el código. El constructor PathGradientBrush del ejemplo recibe una matriz de puntos, pero no requiere un objeto GraphicsPath. Observe también que se usa PathGradientBrush para rellenar un rectángulo, no un trazado. El rectángulo es mayor que el trazado cerrado utilizado para definir el pincel, por lo que el pincel no pinta parte del rectángulo. En la ilustración siguiente se muestra el rectángulo (línea de puntos) y la parte del rectángulo que pinta el pincel de degradado de trazado:

    Parte degradada pintada con el pincel de degradado de trazado.

    public void DrawPathGradentWthoutGraphicsPath(PaintEventArgs e)
    {
        // Construct a path gradient brush based on an array of points.
        PointF[] ptsF = {
           new PointF(0, 0),
           new PointF(160, 0),
           new PointF(160, 200),
           new PointF(80, 150),
           new PointF(0, 200)};
    
        PathGradientBrush pBrush = new PathGradientBrush(ptsF);
    
        // An array of five points was used to construct the path gradient
        // brush. Set the color of each point in that array.
        Color[] colors = {
           Color.FromArgb(255, 255, 0, 0),  // (0, 0) red
           Color.FromArgb(255, 0, 255, 0),  // (160, 0) green
           Color.FromArgb(255, 0, 255, 0),  // (160, 200) green
           Color.FromArgb(255, 0, 0, 255),  // (80, 150) blue
           Color.FromArgb(255, 255, 0, 0)}; // (0, 200) red
    
        pBrush.SurroundColors = colors;
    
        // Set the center color to white.
        pBrush.CenterColor = Color.White;
    
        // Use the path gradient brush to fill a rectangle.
        e.Graphics.FillRectangle(pBrush, new Rectangle(0, 0, 160, 200));
    }
    
    ' Construct a path gradient brush based on an array of points.
    Dim ptsF As PointF() = { _
       New PointF(0, 0), _
       New PointF(160, 0), _
       New PointF(160, 200), _
       New PointF(80, 150), _
       New PointF(0, 200)}
    
    Dim pBrush As New PathGradientBrush(ptsF)
    
    ' An array of five points was used to construct the path gradient
    ' brush. Set the color of each point in that array.  
    'Point (0, 0) is red
    'Point (160, 0) is green
    'Point (160, 200) is green
    'Point (80, 150) is blue
    'Point (0, 200) is red
    Dim colors As Color() = { _
       Color.FromArgb(255, 255, 0, 0), _
       Color.FromArgb(255, 0, 255, 0), _
       Color.FromArgb(255, 0, 255, 0), _
       Color.FromArgb(255, 0, 0, 255), _
       Color.FromArgb(255, 255, 0, 0)}
    pBrush.SurroundColors = colors
    
    ' Set the center color to white.
    pBrush.CenterColor = Color.White
    
    ' Use the path gradient brush to fill a rectangle.
    e.Graphics.FillRectangle(pBrush, New Rectangle(0, 0, 160, 200))
    

Para personalizar un degradado de trazado

  • Una manera de personalizar un pincel de degradado de trazado consiste en establecer su propiedad FocusScales. Las escalas de foco especifican un trazado interior que se encuentra dentro del trazado principal. El color central se muestra en todo ese trazado interior, en lugar de solo en el punto central.

    En el ejemplo siguiente se crea un pincel de degradado de trazado basado en un trazado elíptico. El código establece el color del límite en azul y el color central en aguamarina y, luego, usa el pincel de degradado de trazado para rellenar el trazado elíptico.

    Después, el código establece las escalas de foco del pincel de degradado de trazado. La escala de foco x se establece en 0,3 y la escala de foco y se establece en 0,8. El código llama al método TranslateTransform de un objeto Graphics para que la llamada posterior a FillPath rellene una elipse que se encuentra a la derecha de la primera elipse.

    Para ver el efecto de las escalas de foco, imagine una pequeña elipse que comparte su centro con la elipse principal. La elipse pequeña (la interior) es la elipse principal escalada (alrededor de su centro) horizontalmente por un factor de 0,3 y verticalmente por un factor de 0,8. A medida que se mueve del límite de la elipse exterior al límite de la elipse interior, el color cambia gradualmente de azul a aguamarina. Al moverse del límite de la elipse interior al centro compartido, el color sigue siendo aguamarina.

    En la siguiente ilustración se muestra el resultado del código siguiente. La elipse de la izquierda es aguamarina solo en el punto central. La elipse de la derecha es aguamarina en todo el trazado interior.

Efecto degradado de las escalas de enfoque

public void CustomizePathGradientBrush(PaintEventArgs e)
{
    // Create a path that consists of a single ellipse.
    GraphicsPath path = new GraphicsPath();
    path.AddEllipse(0, 0, 200, 100);

    // Create a path gradient brush based on the elliptical path.
    PathGradientBrush pthGrBrush = new PathGradientBrush(path);

    // Set the color along the entire boundary to blue.
    Color[] color = { Color.Blue };
    pthGrBrush.SurroundColors = color;

    // Set the center color to aqua.
    pthGrBrush.CenterColor = Color.Aqua;

    // Use the path gradient brush to fill the ellipse.
    e.Graphics.FillPath(pthGrBrush, path);

    // Set the focus scales for the path gradient brush.
    pthGrBrush.FocusScales = new PointF(0.3f, 0.8f);

    // Use the path gradient brush to fill the ellipse again.
    // Show this filled ellipse to the right of the first filled ellipse.
    e.Graphics.TranslateTransform(220.0f, 0.0f);
    e.Graphics.FillPath(pthGrBrush, path);
}
' Create a path that consists of a single ellipse.
Dim path As New GraphicsPath()
path.AddEllipse(0, 0, 200, 100)

' Create a path gradient brush based on the elliptical path.
Dim pthGrBrush As New PathGradientBrush(path)

' Set the color along the entire boundary to blue.
' Changed variable name from color
Dim blueColor As Color() = {Color.Blue}
pthGrBrush.SurroundColors = blueColor

' Set the center color to aqua.
pthGrBrush.CenterColor = Color.Aqua

' Use the path gradient brush to fill the ellipse. 
e.Graphics.FillPath(pthGrBrush, path)

' Set the focus scales for the path gradient brush.
pthGrBrush.FocusScales = New PointF(0.3F, 0.8F)

' Use the path gradient brush to fill the ellipse again.
' Show this filled ellipse to the right of the first filled ellipse.
e.Graphics.TranslateTransform(220.0F, 0.0F)
e.Graphics.FillPath(pthGrBrush, path)

Para personalizar con interpolación

  • Otra manera de personalizar un pincel de degradado de ruta consiste en especificar una matriz de colores de interpolación y una matriz de posiciones de interpolación.

    En el ejemplo siguiente se crea un pincel de degradado de trazado basado en un triángulo. El código establece la propiedad InterpolationColors del pincel de degradado de trazado para especificar una matriz de colores de interpolación (verde oscuro, aguamarina y azul) y una matriz de posiciones de interpolación (0, 0.25, 1). A medida que se mueve del límite del triángulo al punto central, el color cambia gradualmente de verde oscuro a aguamarina y, luego, de aguamarina a azul. El cambio de verde oscuro a aguamarina se produce en un 25 % de la distancia que media entre el verde oscuro y el azul.

    En la ilustración siguiente se muestra el triángulo rellenado con el pincel de degradado de trazado personalizado.

    Triángulo relleno con el pincel de degradado de trazado personalizado.

    public void CustomizeWithInterpolation(PaintEventArgs e)
    {
        // Vertices of the outer triangle
        Point[] points = {
           new Point(100, 0),
           new Point(200, 200),
           new Point(0, 200)};
    
        // No GraphicsPath object is created. The PathGradientBrush
        // object is constructed directly from the array of points.
        PathGradientBrush pthGrBrush = new PathGradientBrush(points);
    
        Color[] colors = {
           Color.FromArgb(255, 0, 128, 0),    // dark green
           Color.FromArgb(255, 0, 255, 255),  // aqua
           Color.FromArgb(255, 0, 0, 255)};   // blue
    
        float[] relativePositions = {
           0f,       // Dark green is at the boundary of the triangle.
           0.4f,     // Aqua is 40 percent of the way from the boundary
                     // to the center point.
           1.0f};    // Blue is at the center point.
    
        ColorBlend colorBlend = new ColorBlend();
        colorBlend.Colors = colors;
        colorBlend.Positions = relativePositions;
        pthGrBrush.InterpolationColors = colorBlend;
    
        // Fill a rectangle that is larger than the triangle
        // specified in the Point array. The portion of the
        // rectangle outside the triangle will not be painted.
        e.Graphics.FillRectangle(pthGrBrush, 0, 0, 200, 200);
    }
    
    ' Vertices of the outer triangle
    Dim points As Point() = { _
       New Point(100, 0), _
       New Point(200, 200), _
       New Point(0, 200)}
    
    ' No GraphicsPath object is created. The PathGradientBrush
    ' object is constructed directly from the array of points.
    Dim pthGrBrush As New PathGradientBrush(points)
    
    ' Create an array of colors containing dark green, aqua, and  blue.
    Dim colors As Color() = { _
       Color.FromArgb(255, 0, 128, 0), _
       Color.FromArgb(255, 0, 255, 255), _
       Color.FromArgb(255, 0, 0, 255)}
    
    ' Dark green is at the boundary of the triangle.
    ' Aqua is 40 percent of the way from the boundary to the center point.
    ' Blue is at the center point.
    Dim relativePositions As Single() = { _
       0.0F, _
       0.4F, _
       1.0F}
    
    Dim colorBlend As New ColorBlend()
    colorBlend.Colors = colors
    colorBlend.Positions = relativePositions
    pthGrBrush.InterpolationColors = colorBlend
    
    ' Fill a rectangle that is larger than the triangle
    ' specified in the Point array. The portion of the
    ' rectangle outside the triangle will not be painted.
    e.Graphics.FillRectangle(pthGrBrush, 0, 0, 200, 200)
    
    

Para establecer el punto central

  • De forma predeterminada, el punto central de un pincel de degradado de trazado se encuentra en el centroide del trazado utilizado para construir el pincel. Puede cambiar la ubicación del punto central si establece la propiedad CenterPoint de la clase PathGradientBrush.

    En el ejemplo siguiente se crea un pincel de degradado de trazado basado en una elipse. El centro de la elipse está en (70, 35), pero el punto central del pincel de degradado de trazado se establece en (120, 40).

    public void SetCenterPoint(PaintEventArgs e)
    {
        // Create a path that consists of a single ellipse.
        GraphicsPath path = new GraphicsPath();
        path.AddEllipse(0, 0, 140, 70);
    
        // Use the path to construct a brush.
        PathGradientBrush pthGrBrush = new PathGradientBrush(path);
    
        // Set the center point to a location that is not
        // the centroid of the path.
        pthGrBrush.CenterPoint = new PointF(120, 40);
    
        // Set the color at the center of the path to blue.
        pthGrBrush.CenterColor = Color.FromArgb(255, 0, 0, 255);
    
        // Set the color along the entire boundary
        // of the path to aqua.
        Color[] colors = { Color.FromArgb(255, 0, 255, 255) };
        pthGrBrush.SurroundColors = colors;
    
        e.Graphics.FillEllipse(pthGrBrush, 0, 0, 140, 70);
    }
    
    ' Create a path that consists of a single ellipse.
    Dim path As New GraphicsPath()
    path.AddEllipse(0, 0, 140, 70)
    
    ' Use the path to construct a brush.
    Dim pthGrBrush As New PathGradientBrush(path)
    
    ' Set the center point to a location that is not
    ' the centroid of the path.
    pthGrBrush.CenterPoint = New PointF(120, 40)
    
    ' Set the color at the center of the path to blue.
    pthGrBrush.CenterColor = Color.FromArgb(255, 0, 0, 255)
    
    ' Set the color along the entire boundary 
    ' of the path to aqua.
    Dim colors As Color() = {Color.FromArgb(255, 0, 255, 255)}
    pthGrBrush.SurroundColors = colors
    
    e.Graphics.FillEllipse(pthGrBrush, 0, 0, 140, 70)
    

    En la ilustración siguiente se muestra la elipse rellenada y el punto central del pincel de degradado de trazado:

    Trazado de degradado con la elipse rellenada y un punto central.

  • Puede establecer el punto central de un pincel de degradado de trazado en una ubicación situada fuera del trazado que se usó para construir el pincel. En el ejemplo siguiente se reemplaza la llamada para establecer la propiedad CenterPoint en el código anterior.

    public void SetCenterPointOutsidePath(PaintEventArgs e)
    {
        // Create a path that consists of a single ellipse.
        GraphicsPath path = new GraphicsPath();
        path.AddEllipse(0, 0, 140, 70);
    
        // Use the path to construct a brush.
        PathGradientBrush pthGrBrush = new PathGradientBrush(path);
    
        // Set the center point to a location that is not
        // the centroid of the path.
        pthGrBrush.CenterPoint = new PointF(145, 35);
    
        // Set the color at the center of the path to blue.
        pthGrBrush.CenterColor = Color.FromArgb(255, 0, 0, 255);
    
        // Set the color along the entire boundary
        // of the path to aqua.
        Color[] colors = { Color.FromArgb(255, 0, 255, 255) };
        pthGrBrush.SurroundColors = colors;
    
        e.Graphics.FillEllipse(pthGrBrush, 0, 0, 140, 70);
    }
    
    pthGrBrush.CenterPoint = New PointF(145, 35)
    

    En la ilustración siguiente se muestra el resultado de este cambio:

    Trazado de degradado con un punto central fuera del trazado.

    En la ilustración anterior, los puntos situados en el extremo derecho de la elipse no son de color azul puro (aunque están muy cerca). Los colores del degradado se colocan como si el relleno alcanzara el punto (145, 35) donde el color sería azul puro (0, 0, 255). Pero el relleno nunca alcanza (145, 35) porque un pincel de degradado de trazado solo pinta dentro de su trazado.

Compilar el código

Los ejemplos anteriores están diseñados para su uso con Windows Forms y requieren PaintEventArgse, que es un parámetro del controlador de eventos Paint.

Consulte también