我正在捕获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;
}
答案 0 :(得分:1)
正如在问题评论中已经提到的那样,你必须在渲染元素之前渲染一个背景矩形:
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;
}