我需要一个单个画笔,可以从一种颜色到下一种颜色进行硬过渡,如下所示。我提供了另一个控件的填充画笔,因此我需要一个画笔对象。
我想要什么:
我尝试了LinearGradientBrush
多种方法(参见下面的一个示例),但它不会产生硬线;过渡仍然是渐变并且线条模糊。
LinearGradientBrush brush = new LinearGradientBrush(pictureBox1.ClientRectangle, Color.Green, Color.Silver, 0f);
Blend blend = new Blend();
blend.Factors = new float[] { 0, 0, 1, 1 };
blend.Positions = new float[] { 0, .7f, .7f, 1 };
brush.Blend = blend;
我得到了什么:
如何定义单个画笔来执行此操作?
最佳答案
为此,您可能需要使用 TexureBrush
。
TextureBrush
将图像作为参数,这意味着您可以从光盘加载现有图像,或者在内存中创建一个图像,然后在其中绘制矩形等。
在下面的示例中,GetTextureBrush 将创建实际的画笔。您可以在此处定义颜色和形状。我刚刚根据您的需要创建了一些东西,请根据需要进行调整。
例如(VB.net):
Private Sub DrawBrush()
Dim g As Graphics = Me.CreateGraphics
Dim bmp As Image = GetTexureBrush
Dim b As New TextureBrush(bmp)
g.FillRectangle(b, New Rectangle(0, 0, 200, 500))
b.Dispose()
bmp.Dispose()
g.Dispose()
End Sub
Private Function GetTexureBrush() As Image
Dim bmp As New Bitmap(100, 20)
Dim g As Graphics = Graphics.FromImage(bmp)
g.FillRectangle(Brushes.DarkGreen, New Rectangle(0, 0, 75, 20))
g.FillRectangle(Brushes.Gray, New Rectangle(75, 0, 25, 20))
g.Dispose()
Return bmp
End Function
C#
private void DrawBrush()
{
Graphics g = this.CreateGraphics;
Image bmp = GetTexureBrush();
TextureBrush b = new TextureBrush(bmp);
g.FillRectangle(b, new Rectangle(0, 0, 200, 500));
b.Dispose();
bmp.Dispose();
g.Dispose();
}
private Image GetTexureBrush()
{
Bitmap bmp = new Bitmap(100, 20);
Graphics g = Graphics.FromImage(bmp);
g.FillRectangle(Brushes.DarkGreen, new Rectangle(0, 0, 75, 20));
g.FillRectangle(Brushes.Gray, new Rectangle(75, 0, 25, 20));
g.Dispose();
return bmp;
}
关于具有硬颜色过渡的.NET画笔(类似于渐变),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13519528/