我尝试使用BufferedGraphics做双缓冲。当我使用BufferedGraphics.Render方法时,我的图像背景变为黑色。这里是简单的代码,用于说明我的问题
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 :(得分: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);
}
}
在结果中,您可以清楚地看到背景缓冲区中红色背景上图像的蓝线(红色背景未被覆盖),红色矩形周围有黑色边框,没有绘制背景像素。