繁体   English   中英

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

[英]C# - Gradient over picture in picturebox

我已经在VB.NET中开发了一个应用程序,现在我将其移至C#。

到目前为止,一切进展顺利,但我面临一个问题。

我有一个在其中有图片的pictureBox。 在此图片框上,我希望渐变从顶部透明到颜色“控件”,以与表单背景色融合。 我已经在可以正常工作的VB.net中完成了此操作,但是当我尝试在C#中执行此操作时,似乎绘制了渐变,但是在图片后面。

这是我尝试过的:

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();
}   

但是,这实际上似乎确实有效,但是它再次在图片后面绘制了渐变。 在VB.net中,它无需任何额外代码即可将其绘制在图片上方。

我是否需要添加任何其他内容?

如果有关系,请在C#2010 Express中进行即时编码。

以下代码可以做到这一点。

我可能会考虑使其成为自己的控件,并使用以下代码作为其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);
    }

此代码产生以下图像

在此处输入图片说明

暂无
暂无

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

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