1

我正在捕获 FrameworkElement 的屏幕截图并保存为 png 文件。但是我想禁用 png 的背景透明度。我怎么做?

我没有选择 JpegBitmapEncoder 因为它不能正确渲染 DropShadowEffect。以下是代码片段

    private void EncodeAndSaveToFile(string fileName)
    {
        var bitmapSource = FrameworkElement.RenderToBitmap();
        if (bitmapSource != null)
        {
            using (var stream = new FileStream(fileName, FileMode.Create))
            {
                var encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
                encoder.Save(stream);
            }
        }
    }


    public static BitmapSource RenderToBitmap(this UIElement element, double scale)
    {

        var renderWidth = (int)(element.RenderSize.Width * scale);
        var renderHeight = (int)(element.RenderSize.Height * scale);

        var renderTarget = new RenderTargetBitmap(renderWidth, renderHeight, 96, 96, PixelFormats.Pbgra32);
        var sourceBrush = new VisualBrush(element);


        var drawingVisual = new DrawingVisual();
        var drawingContext = drawingVisual.RenderOpen();

        using (drawingContext)
        {
            drawingContext.PushTransform(new ScaleTransform(scale, scale));
            drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(element.RenderSize.Width, element.RenderSize.Height)));
        }
        renderTarget.Render(drawingVisual);

        return renderTarget;
    }
4

1 回答 1

2

正如对该问题的评论中已经提到的,您必须在渲染元素之前渲染一个背景矩形:

public static BitmapSource RenderToBitmap(
    this UIElement element, double scale, Brush background)
{
    var renderWidth = (int)(element.RenderSize.Width * scale);
    var renderHeight = (int)(element.RenderSize.Height * scale);

    var renderTarget = new RenderTargetBitmap(renderWidth, renderHeight,
                                              96, 96, PixelFormats.Default);
    var sourceBrush = new VisualBrush(element);

    var drawingVisual = new DrawingVisual();
    var drawingContext = drawingVisual.RenderOpen();

    var rect = new Rect(0, 0, element.RenderSize.Width, element.RenderSize.Height);

    using (drawingContext)
    {
        drawingContext.PushTransform(new ScaleTransform(scale, scale));
        drawingContext.DrawRectangle(background, null, rect); // here
        drawingContext.DrawRectangle(sourceBrush, null, rect);
    }

    renderTarget.Render(drawingVisual);

    return renderTarget;
}
于 2013-10-23T06:06:51.780 回答