.netgdi+brushlineargradientbrush

.NET Brush with hard color transition (similar to gradient)


I need a single Brush that will make a hard transition from one color to the next like shown below. I'm providing the Fill Brush of another control, so I need a single Brush object.

What I want:

http://mechgt.com/dump/sample.png

I've tried LinearGradientBrush several ways (see below as one example), but it doesn't produce a hard line; the transition is still a gradient and the line is blurred.

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;

What I get:

http://mechgt.com/dump/sample2.png

How do I define a single brush that will do this?


Solution

  • For this you will probably need to use a TexureBrush.

    The TextureBrush takes an image as parameter so that means you can either load an existing image from disc, or create an image in memory which you draw rectangles etc. to.

    In the following example the GetTextureBrush will create the actual brush. Here is where you define the colors and shape. I just created something in the lane of what you need, adjust as needed.

    For example (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;
    
    }