简体   繁体   English

C#-图片框中图片的渐变

[英]C# - Gradient over picture in picturebox

I have developed an application in VB.NET that I'm now moving over to C#. 我已经在VB.NET中开发了一个应用程序,现在我将其移至C#。

Everything is going smooth so far, but I'm facing one problem. 到目前为止,一切进展顺利,但我面临一个问题。

I have a pictureBox that has a picture in it. 我有一个在其中有图片的pictureBox。 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. 我已经在可以正常工作的VB.net中完成了此操作,但是当我尝试在C#中执行此操作时,似乎绘制了渐变,但是在图片后面。

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.. 在VB.net中,它无需任何额外代码即可将其绘制在图片上方。

Do i need to add anything extra? 我是否需要添加任何其他内容?

If it matters im coding in C# 2010 express. 如果有关系,请在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. 我可能会考虑使其成为自己的控件,并使用以下代码作为其Paint事件。

    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 此代码产生以下图像

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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