Compartir a través de


Cómo: Crear un degradado de ruta de acceso

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

Nota:

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

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

Para rellenar una elipse con un degradado de camino

  • 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 se establece en aqua. En la ilustración siguiente se muestra la elipse rellenada.

    Trazado degradado rellena una elipse.

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

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

    El gradiente se extendió más allá del límite del camino.

    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 el PaintEventArgs e, 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 trayectoria a partir de una trayectoria con forma de estrella. El código establece la CenterColor propiedad , que establece el color en el centroide de la estrella en rojo. A continuación, el código establece la SurroundColors propiedad para especificar varios colores (almacenados en la colors matriz) en los puntos individuales de la points matriz. La instrucción de código final rellena el camino con forma de estrella usando el pincel de degradado de ruta.

    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 siguiente ejemplo se dibuja un degradado de trayectoria sin un objeto GraphicsPath en el código. El constructor concreto PathGradientBrush del ejemplo recibe una matriz de puntos, pero no requiere un GraphicsPath objeto . Además, tenga en cuenta que PathGradientBrush se usa para rellenar un rectángulo, no una ruta de acceso. El rectángulo es más grande que la trayectoria cerrada que se usa para definir el pincel, por lo que parte del rectángulo no está cubierta por el pincel. En la ilustración siguiente se muestra el rectángulo (línea de puntos) y la parte del rectángulo pintada por el pincel de gradiente de trayectoria.

    Parte degradada pintada por el pincel de gradiente 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 trayecto

  • Una manera de personalizar un pincel de degradado de trazado es establecer la propiedad FocusScales. Las escalas de foco especifican una ruta de acceso interna que se encuentra dentro de la ruta de acceso principal. El color central se muestra en todas partes dentro de esa ruta interna en lugar de solo en el punto central.

    En el ejemplo siguiente se crea un pincel de degradado de ruta basado en una ruta elíptica. El código establece el color del límite en azul, establece el color central en aguamarina y, a continuación, usa el pincel de degradado de ruta para rellenar la ruta elíptica.

    A continuación, el código establece las escalas de los puntos de enfoque del pincel de degradado de la ruta. 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 del objeto Graphics para que la llamada posterior al 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 (interna) es la elipse principal escalada (en torno a 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 aqua. A medida que se mueve del límite de la elipse interior al centro compartido, el color permanece aguamarina.

    En la ilustración siguiente se muestra la salida del código siguiente. La elipse de la izquierda es de color aguamarina solo en el punto central. La elipse a la derecha es de color aguamarina en toda la trayectoria interior.

Efecto de 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 es especificar una matriz de colores de interpolación y una matriz de posiciones de interpolación.

    En el siguiente ejemplo se crea un pincel de degradado de camino basado en un triángulo. El código establece la InterpolationColors propiedad del pincel degradado de ruta para especificar una matriz de colores de interpolación (verde oscuro, aqua, 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 aqua y luego de aqua a azul. El cambio de verde oscuro a aqua se produce en el 25 por ciento de la distancia de verde oscuro a azul.

    En la ilustración siguiente se muestra el triángulo relleno con el pincel de degradado de trayectoria personalizada.

    Triángulo relleno con pincel de degradado de trayectoria personalizada.

    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 una brocha de gradiente de trayectoria se encuentra en el centroide del camino que se usa para construir la brocha. Puede cambiar la ubicación del punto central estableciendo la CenterPoint propiedad de la PathGradientBrush clase .

    En el ejemplo siguiente se crea un pincel degradado de ruta 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 siguiente ilustración se muestra la elipse rellena y el punto central del pincel de degradado de trayectoria.

    Trazado degradado con elipse rellena y punto en el centro.

  • Puede establecer el punto central de un pincel de degradado de trayectoria en una ubicación fuera de la trayectoria que se usó para construir el pincel. En el ejemplo siguiente se reemplaza la llamada para establecer la CenterPoint propiedad 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 la salida con este cambio:

    Trayectoria de degradado con punto central fuera de la trayectoria.

    En la ilustración anterior, los puntos situados en el extremo derecho de la elipse no son azules puros (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 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 Paint controlador de eventos.

Consulte también