2015-12-03 86 views
1

我嘗試使用BufferedGraphics進行雙緩衝。當我使用BufferedGraphics.Render方法將我的圖像背景變爲黑色時。這裏的簡單代碼,說明我的問題Bufferedgraphics將背景更改爲黑色c#

public partial class Form1 : Form { 
    public Form1() { 
     InitializeComponent(); 
     this.Load += Form1_Load; 
    } 
    private void Form1_Load(object sender, EventArgs e) { 
     Paint += new PaintEventHandler(Form1_Paint); 
    } 
    private void print(Bitmap image, PaintEventArgs e) { 
     Graphics graphicsObj = e.Graphics; 
     graphicsObj.DrawImage(image, 60, 10); 
     graphicsObj.Dispose(); 
    } 

    private void Form1_Paint(object sender, PaintEventArgs e) { 
     Rectangle rect = Screen.PrimaryScreen.Bounds; 
     PixelFormat pf; 
     pf = PixelFormat.Format32bppArgb; 
     Bitmap image = new Bitmap(rect.Width, rect.Height, pf); 

     Graphics g = Graphics.FromImage(image); 
     g.Clear(Color.Orange); 

     BufferedGraphicsContext context = new BufferedGraphicsContext(); 
     BufferedGraphics buffer = context.Allocate(g, new Rectangle(0, 0, rect.Width + 20, rect.Height + 20)); 
     buffer.Render(g); 

     print(image, e); 
    } 
} 

我希望看到我的屏幕上的橙色矩形,但它是黑色的。我不明白爲什麼會發生這種情況。請幫助我:)

回答

0

buffer.Render(g)呈現緩衝區內容的圖形對象。這意味着橙色將被空緩衝區覆蓋。

您必須選擇使用BufferedGraphicsContext或自己創建緩衝區(圖像)。

下將只使用圖像解決您的問題:

... 
Bitmap image = new Bitmap(rect.Width, rect.Height, pf); 
using (Graphics g = Graphics.FromImage(image)) 
{ 
    g.Clear(Color.Orange); 
} 

print(image, e); 

你也可以仍然使用BufferedGraphicsContext,但你必須將圖像寫入其Graphics屬性:

print(image, buffer.Graphics); // render your image to the buffer 
buffer.Render(e.Graphics); // render the buffer to the paint event graphics 

順便說一下,不要Dispose提供的圖形對象Form1_Paint(您目前在做print()方法。

作爲對您的評論的回覆,BufferedGraphicsContext在將其渲染到「主」圖形對象時似乎不支持透明度,但您可以正確地繪製透明圖像。下面的例子顯示了緩衝區是如何充滿了紅色,然後用藍線透明圖像被吸引到它:

protected override void OnPaint(PaintEventArgs e) 
{ 
    base.OnPaint(e); 

    using (BufferedGraphicsContext context = new BufferedGraphicsContext()) 
    using (BufferedGraphics buffer = context.Allocate(e.Graphics, new Rectangle(0, 0, 120, 120))) 
    { 
     // Create a bitmap with just a blue line on it 
     Bitmap bmp = new Bitmap(100, 100, PixelFormat.Format32bppArgb); 
     using (Graphics g = Graphics.FromImage(bmp)) 
     { 
      g.DrawLine(Pens.Blue, 0, 0, 100, 100); 
     } 

     // Fill a red square 
     buffer.Graphics.FillRectangle(Brushes.Red, 5, 5, 110, 110); 
     // Draw the blue-line image over the red square area 
     buffer.Graphics.DrawImage(bmp, 10, 10); 
     // Render the buffer to the underlying graphics 
     buffer.Render(e.Graphics); 
    } 
} 

在結果中可以清楚地看到藍線從圖像過背景緩衝區中的紅色(紅色背景未被覆蓋),並且紅色矩形周圍有一個黑色邊框,其中沒有繪製背景像素。

+0

我可以更改緩衝區內容的背景嗎?在我的工作項目中,我使用緩衝區中的透明背景添加圖像,並且當我將其渲染到圖形背景時更改爲黑色 – Alex

+0

謝謝您的回答。這是幫助 – Alex

相關問題