2013-10-02 101 views
2

我在VB.NET中開發了一個應用程序,現在我正轉向C#。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中重要的編碼。

+1

這似乎並不可能是語言切換本身會導致此問題。一個正在執行的程序不知道它最初寫的是什麼語言。你能發佈你的原始VB.NET代碼嗎? – vcsjones

+1

發佈的代碼工作正常。 – LarsTech

+0

爲什麼你通過ref傳遞PictureBox1? –

回答

3

以下代碼執行此操作。

我也許會考慮將它作爲自己的控件,並將下面的代碼用作其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); 
    } 

此代碼將產生以下圖像

enter image description here

+0

嗯,我看到的唯一真正的區別是使用ClientRectangle而不是DisplayRectangle。然而,我不能讓它工作 –

+0

然後你的代碼中必須有一些其他的渲染代碼發生。你有沒有重寫OnPaintBackground事件?我通過1)在我的項目中添加一個新窗體,2)從工具箱中將一個圖框放到它上面,3)在我的窗體中註冊Paint事件並使用上面的代碼,在圖像上生成透明漸變。嘗試上述步驟,它會工作。 –

+0

更改頂部和底部的顏色,不要忘記設置透明度,以便您可以看到您的「背景圖像」。 Color.Transparent和Color.Control作爲漸變顏色會產生難以看清的漸變。嘗試使用: Color top = Color.FromArgb(128,Color.Blue); Color bottom = Color.FromArgb(128,Color.Red); –