Como: Criar um gradiente de caminho
A classe PathGradientBrush permite que você personalize a maneira como preenche uma forma com cores que mudam gradualmente. Por exemplo, você pode especificar uma cor para o centro de um caminho e outra cor para o limite de um caminho. Você também pode especificar cores separadas para cada um dos vários pontos ao longo do limite de um caminho.
Observação
Em GDI+, um caminho é uma sequência de linhas e curvas mantida por um objeto GraphicsPath. Para mais informações sobre caminhos em GDI+, consulte Caminhos Gráficos em GDI+ e Construção e Desenho de Caminhos.
Os exemplos neste artigo são métodos que são chamados a partir de um manipulador de eventos Paint de controle.
Para preencher uma elipse com um gradiente do caminho
O exemplo a seguir preenche uma elipse com um pincel de gradiente de trajetória. A cor central é definida como azul e a cor do limite é definida como aqua. A ilustração a seguir mostra a elipse preenchida.
Por padrão, um pincel de gradiente de caminho não se estende para fora do limite do caminho. Se utilizar o pincel de gradiente de percurso para preencher uma forma que se estenda além do limite do percurso, a área da tela fora do percurso não será preenchida.
A ilustração a seguir mostra o que acontece se você alterar a chamada de Graphics.FillEllipse no código a seguir para
e.Graphics.FillRectangle(pthGrBrush, 0, 10, 200, 40)
: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)
O exemplo de código anterior foi projetado para uso com o Windows Forms e requer o PaintEventArgs e, que é um parâmetro de PaintEventHandler.
Para especificar pontos no limite
O exemplo a seguir constrói um pincel de gradiente de caminho a partir de uma trajetória em forma de estrela. O código define a propriedade CenterColor, que define a cor no centróide da estrela como vermelho. Em seguida, o código define a propriedade SurroundColors para especificar várias cores (armazenadas na matriz
colors
) nos pontos individuais da matrizpoints
. A instrução de código final preenche o caminho em forma de estrela com o pincel de gradiente de trajeto.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)
O exemplo a seguir desenha um gradiente de caminho sem um objeto GraphicsPath no código. O construtor PathGradientBrush particular no exemplo recebe uma matriz de pontos, mas não requer um objeto GraphicsPath. Além disso, observe que o PathGradientBrush é usado para preencher um retângulo, não um caminho. O retângulo é maior do que o caminho fechado usado para definir o pincel, portanto, parte do retângulo não é pintado pelo pincel. A ilustração a seguir mostra o retângulo (linha pontilhada) e a parte do retângulo pintada pelo pincel de gradiente de trajetória.
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 um gradiente de caminho
Uma maneira de personalizar um pincel de gradiente de caminho é definir sua propriedade FocusScales. As escalas de foco especificam um caminho interno que fica dentro do caminho principal. A cor central é exibida em todos os lugares dentro desse caminho interno, em vez de apenas no ponto central.
O exemplo a seguir cria um pincel de gradiente de percurso com base num caminho elíptico. O código define a cor do limite como azul, define a cor do centro como aquamarina e, em seguida, utiliza o pincel de gradiente de trajetória para preencher o caminho elíptico.
Em seguida, o código define as escalas de foco do pincel de gradiente de caminho. A escala de foco x é definida como 0,3 e a escala de foco y é definida como 0,8. O código chama o método TranslateTransform de um objeto Graphics para que a chamada subsequente para FillPath preencha uma elipse que fica à direita da primeira elipse.
Para ver o efeito das escalas de foco, imagine uma pequena elipse que compartilha seu centro com a elipse principal. A pequena elipse (interna) é a elipse principal dimensionada (aproximadamente ao seu centro) horizontalmente por um fator de 0,3 e verticalmente por um fator de 0,8. À medida que você se move do limite da elipse externa para o limite da elipse interna, a cor muda gradualmente de azul para água. À medida que você se move do limite da elipse interna para o centro compartilhado, a cor permanece aquosa.
A ilustração a seguir mostra a saída do código a seguir. A elipse à esquerda é cor de água só no ponto central. A elipse do lado direito é de cor de água por toda a parte dentro do caminho interior.
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 com interpolação
Outra maneira de personalizar um pincel de gradiente de caminho é especificar uma matriz de cores de interpolação e uma matriz de posições de interpolação.
O exemplo seguinte cria um pincel de gradiente de trajetória baseado num triângulo. O código define a propriedade InterpolationColors do pincel de gradiente de caminho para especificar uma matriz de cores de interpolação (verde escuro, aqua, azul) e uma matriz de posições de interpolação (0, 0,25, 1). À medida que você se move do limite do triângulo para o ponto central, a cor muda gradualmente de verde escuro para aqua e, em seguida, de aqua para azul. A mudança de verde escuro para aqua acontece em 25% da distância de verde escuro para azul.
A ilustração seguinte mostra um triângulo preenchido com um pincel de gradiente de caminho 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 definir o ponto central
Por padrão, o ponto central de um pincel de gradiente de caminho está no centróide do caminho usado para construir o pincel. Você pode alterar o local do ponto central definindo a propriedade CenterPoint da classe PathGradientBrush.
O exemplo a seguir cria um pincel de gradiente de trajetória com base em uma elipse. O centro da elipse está em (70, 35), mas o ponto central do pincel de gradiente de percurso está definido em (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)
A ilustração a seguir mostra a elipse preenchida e o ponto central do pincel de gradiente de trajetória:
Pode definir o ponto central de um pincel de gradiente de percurso para uma localização fora do percurso que foi utilizado para construir o pincel. O exemplo a seguir substitui a chamada para definir a propriedade CenterPoint no 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)
A ilustração a seguir mostra o resultado com esta alteração.
Na ilustração anterior, os pontos na extremidade direita da elipse não são azuis puros (embora estejam muito próximos). As cores no gradiente são posicionadas como se o preenchimento atingisse o ponto (145, 35) onde a cor seria azul puro (0, 0, 255). Mas o preenchimento nunca chega a (145, 35) porque um pincel com gradiente de percurso pinta apenas dentro do seu caminho.
Compilando o código
Os exemplos anteriores foram projetados para uso com o Windows Forms e exigem PaintEventArgse
, que é um parâmetro do manipulador de eventos Paint.
Ver também
.NET Desktop feedback