Winforms C# Gradient Opacity bitmap

孤街浪徒 提交于 2019-12-24 12:26:10

问题


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.


回答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:




回答2:


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.



来源:https://stackoverflow.com/questions/22452740/winforms-c-sharp-gradient-opacity-bitmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!