简体   繁体   中英

C# - Gradient over picture in picturebox

I have developed an application in VB.NET that I'm now moving over to C#.

Everything is going smooth so far, but I'm facing one problem.

I have a pictureBox that has a picture in it. Over this picture box I want a gradient to be that goes from transparent at top down to the color "control" to blend in with the forms background color. I have allready done this in VB.net which works, but when im trying to do this in C# the gradient seems to be drawn, but behind the picture.

Here is what i have tried:

private void PictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
    Color top = Color.Transparent;
    Color bottom = Color.FromKnownColor(KnownColor.Control);

    GradientPictureBox(top, bottom, ref PictureBox1, e);
}

public void GradientPictureBox(Color topColor, Color bottomColor, ref PictureBox PictureBox1, System.Windows.Forms.PaintEventArgs e)
{
    LinearGradientMode direction = LinearGradientMode.Vertical;
    LinearGradientBrush brush = new LinearGradientBrush(PictureBox1.DisplayRectangle, topColor, bottomColor, direction);
    e.Graphics.FillRectangle(brush, PictureBox1.DisplayRectangle);
    brush.Dispose();
}   

However this does in fact seem to work, but again it paints the gradient behind the picture. In VB.net it painted it on top of the picture without any extra code..

Do i need to add anything extra?

If it matters im coding in C# 2010 express.

The following code does it.

I would perhaps consider making this its own control, and using the following code as its Paint event.

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.DrawImage(pictureBox1.Image, 0, 0, pictureBox1.ClientRectangle, GraphicsUnit.Pixel);

        Color top = Color.FromArgb(128, Color.Blue);
        Color bottom = Color.FromArgb(128, Color.Red);
        LinearGradientMode direction = LinearGradientMode.Vertical;
        LinearGradientBrush brush = new LinearGradientBrush(pictureBox1.ClientRectangle, top, bottom, direction);

        e.Graphics.FillRectangle(brush, pictureBox1.ClientRectangle);
    }

This code produces the following image

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM