我正在捕获 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;
}