5

我想将我的画布保存为图像。它可以工作,但背景颜色是黑色。我必须如何添加才能改变颜色?

我使用这段代码:

Size size = new Size(surface.Width, surface.Height);

surface.Measure(size);
surface.Arrange(new Rect(size));

// Create a render bitmap and push the surface to it
RenderTargetBitmap renderBitmap =
    new RenderTargetBitmap((int)size.Width, (int)size.Height, 96d, 96d,
                           PixelFormats.Pbgra32);
renderBitmap.Render(surface);

// Create a file stream for saving image
using (FileStream outStream = new FileStream(filename, FileMode.Create))
{
    BmpBitmapEncoder encoder = new BmpBitmapEncoder();
    // push the rendered bitmap to it
    encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
    // save the data to the stream
    encoder.Save(outStream);
}
4

2 回答 2

5

试试这个

Size size = new Size(surface.Width, surface.Height);

surface.Measure(size);
surface.Arrange(new Rect(size));

// Create a render bitmap and push the surface to it
RenderTargetBitmap renderBitmap =
    new RenderTargetBitmap((int)size.Width, (int)size.Height, 96d, 96d,
                           PixelFormats.Pbgra32);

DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext drawingContext = drawingVisual.RenderOpen())
{
    VisualBrush visualBrush = new VisualBrush(surface);
    drawingContext.DrawRectangle(visualBrush, null, 
      new Rect(new Point(), new Size(size.Width, size.Height)));
}

renderBitmap.Render(drawingVisual);

// Create a file stream for saving image
using (FileStream outStream = new FileStream(filename, FileMode.Create))
{
    BmpBitmapEncoder encoder = new BmpBitmapEncoder();
    // push the rendered bitmap to it
    encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
    // save the data to the stream
    encoder.Save(outStream);
}
于 2012-05-30T13:38:35.057 回答
1

尝试PixelFormats.DefaultorPixelFormats.Bgra32PixelFormats.Rgb24代替PixelFormats.Pbgra32.

P代表预乘——假设每个通道都预先乘以 alpha。

MSDN 参考

于 2012-05-30T13:22:45.923 回答