1

I want to make a bitmap that has a linear opacity applied. (i.e. it is more opaque on the left side and get progressively less opaque as it approaches the right.)

Is this possible? I know its possible to have a constant opacity level.

Westy10101
  • 861
  • 2
  • 12
  • 25

2 Answers2

1

I know its possible to have a constant opacity level

So don't make it constant, LinearGradientBrush has no trouble interpolating the alpha value. A simple demonstration of a form that has the BackgroundImage set:

    protected override void OnPaint(PaintEventArgs e) {
        base.OnPaint(e);
        var rc = new Rectangle(20, 20, this.ClientSize.Width - 40, 50);
        using (var brush = new System.Drawing.Drawing2D.LinearGradientBrush(
            rc, 
            Color.FromArgb(255, Color.BlueViolet), 
            Color.FromArgb(0,   Color.BlueViolet), 
            0f)) {
                e.Graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half;
                e.Graphics.FillRectangle(brush, rc);
        }
    }

Produced:

enter image description here

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
0

Put the BitMap into a PictureBox control. Then you will have to use the PictureBox's Paint event handler to do the fading. Something like

private void pictureBox_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.DrawImage(pictureBox.Image, 0, 0, 
        pictureBox.ClientRectangle, GraphicsUnit.Pixel);
    Color left = Color.FromArgb(128, Color.Blue);
    Color right = Color.FromArgb(128, Color.Red);
    LinearGradientMode direction = LinearGradientMode.Horizontal;
    LinearGradientBrush brush = new LinearGradientBrush(
        pictureBox.ClientRectangle, left, right, direction);
    e.Graphics.FillRectangle(brush, pictureBox.ClientRectangle);
}

This example fades the image overlay from blue to red. I am sure you can play with this to get what you want working.

I hope this helps.

MoonKnight
  • 23,214
  • 40
  • 145
  • 277