【问题标题】:C# - Gradient over picture in pictureboxC# - 图片框中的图片渐变
【发布时间】:2013-10-02 19:57:22
【问题描述】:

我已经在 VB.NET 中开发了一个应用程序,现在我正在迁移到 C#。

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

我有一个图片框,里面有一张图片。在这个图片框上,我想要一个渐变,从自上而下的透明到颜色“控制”,以与表单背景颜色融为一体。我已经在 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 中编码很重要。

【问题讨论】:

  • 语言切换本身似乎不太可能导致这种情况。执行程序不知道它最初是用什么语言编写的。你能发布你原来的 VB.NET 代码吗?
  • 发布的代码运行良好。
  • 为什么你通过 ref 传递 PictureBox1?
  • Alessandro D'Andria - 使代码为以后与多个图片框一起使用做好准备。但由于它无法正常工作,我看到的空白内的代码还没有准备好。

标签: c# gradient picturebox


【解决方案1】:

下面的代码可以做到。

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

此代码生成以下图像

【讨论】:

  • 嗯,我看到的唯一真正区别是使用 ClientRectangle 而不是 DisplayRectangle。但是我无法让它工作
  • 那么你的代码中肯定会出现一些其他的渲染代码。您是否有任何机会覆盖 OnPaintBackground 事件?我通过以下方式在图像上生成透明渐变:1)向我的项目添加一个新表单,2)从工具箱中将一个图片框拖放到它上面,3)在我的表单中注册 Paint 事件并使用上面的代码。尝试上述步骤,它会工作。
  • 改变你的顶部和底部颜色,不要忘记设置透明度,这样你就可以看到你的“背景图像”。 Color.Transparent 和 Color.Control 作为您的渐变颜色会产生一个很难看到的渐变。尝试使用: Color top = Color.FromArgb(128, Color.Blue);底色 = Color.FromArgb(128, Color.Red);
  • 对不起,我最近一直很忙,但我现在正在看!感谢您的宝贵时间!我如何“3)在我的表单中注册 Paint 事件”因为那一定是我错过它的地方..
  • 我愿意,但我不能,因为我需要 15 声望才能做到 :(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多