缓冲图形将背景更改为黑色c#

本文关键字:黑色 图形 背景 缓冲 | 更新日期: 2023-09-27 18:25:25

我尝试使用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);
    }
}

我希望在屏幕上看到橙色的矩形,但它是黑色的。我不明白为什么会发生这种事。请帮帮我:)

缓冲图形将背景更改为黑色c#

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

结果,你可以清楚地看到背景缓冲区中红色上方的图像蓝线(红色背景不会被覆盖),红色矩形周围有一个黑色边界,没有绘制背景像素。