To save a visual to an image file need to use RenderTargetBitmap, detail is reference to Save and read images in WPF.

But sometimes you will find the output image was shifted or left blank. This is because that RenderTargetBitmap render the visual object based on cordinate of its parent object. Margin of itself, Padding or BorderThickness of its parent will all affect the rendered image. Although I think this is a bug of WPF, it seems the feature is by design as reference to RenderTargetBitmap layout offset influence.

There are three ways to fix the problem,

Solution Description
Add a Border Simple, but the visual logical tree is changed.
Use a VisualBrush Maintain the original visaul logical tree, but need to do more process.
Temporary change the reative postion by Measure() and Arrange() Need to change back after rendering, and the two function is automatically called while repainting by WPF, so the real process is hard to tell.

The first solution is simplist. RenderTargetBitmap is only shifted by the distance between visaul and its parent object, so you just need to add a fake parent and move the margin to the parent object.

If the original visual logical tree is like

<Grid>
<Canvas Margin="20" />
</Grid>

changed to

<Grid>
<Border Margin="20">
<Canvas />
</Border>
</Grid>

and just call the method of SaveTo as Save and read images in WPF.

private void SaveTo(Visual v, string f)
{
/// get bound of the visual
Rect b = VisualTreeHelper.GetDescendantBounds(v);

/// new a RenderTargetBitmap with actual size of c
RenderTargetBitmap r = new RenderTargetBitmap(
(int)b.Width, (int)b.Height,
96, 96, PixelFormats.Pbgra32);

/// render visual
r.Render(v);

/// new a JpegBitmapEncoder and add r into it
JpegBitmapEncoder e = new JpegBitmapEncoder();
e.Frames.Add(BitmapFrame.Create(r));

/// new a FileStream to write the image file
FileStream s = new FileStream(f,
FileMode.OpenOrCreate, FileAccess.Write);
e.Save(s);
s.Close();
}

Second solution is draw the visaul to a DrawingVisual object, and pass the object to the SaveTo function.

private DrawingVisual ModifyToDrawingVisual(Visual v)
{
/// new a drawing visual and get its context
DrawingVisual dv = new DrawingVisual();
DrawingContext dc = dv.RenderOpen();

/// generate a visual brush by input, and paint
VisualBrush vb = new VisualBrush(v);
dc.DrawRectangle(vb, null, b);
dc.Close();

return dv;
}

PS. The context will act after calling Close(). You can use the using statement to block the region. And the SaveTo method should be modified as

/// render visual
r.Render(ModifyToDrawingVisual(v));

The third solution is to temporarily change the reative postion by Measure and Arrange before Render,

private void ModifyPosition(FrameworkElement fe)
{
/// get the size of the visual with margin
Size fs = new Size(
fe.ActualWidth +
fe.Margin.Left + fe.Margin.Right,
fe.ActualHeight +
fe.Margin.Top + fe.Margin.Bottom);

/// measure the visual with new size
fe.Measure(fs);

/// arrange the visual to align parent with (0,0)
fe.Arrange(new Rect(
-fe.Margin.Left, -fe.Margin.Top,
fs.Width, fs.Height));
}

PS. The solution is only suitable for UIElement, and need to change the position back after rendering.

private void ModifyPositionBack(FrameworkElement fe)
{
/// remeasure a size smaller than need, wpf will
/// rearrange it to the original position
fe.Measure(new Size());
}

Because the size to be measured is smaller then the real size, WPF will rearrange the layout and align the position back. And the render part is modified as

/// render visual
ModifyPosition(v as FrameworkElement);
r.Render(v);
ModifyPositionBack(v as FrameworkElement);

About Measure() and Arrange(), detail is reference toUIElement.Measure Method

--
Reference
RenderTargetBitmap layout offset influence
RenderTargetBitmap tips
RenderTargetBitmap and XamChart - Broken, Redux

Problem of saving images in WPF (RenderTargetBitmap)zz的更多相关文章

  1. wpf RenderTargetBitmap保存控件为图片时图片尺寸不对的问题

    使用RenderTargetBitmap渲染图片时,必须在需要渲染的控件外层包含一个border控件,不然渲染的图片返回就会出现问题. 如下: <Grid> <Grid.RowDef ...

  2. WPF:如何高速更新Model中的属性

    原文:[WPF/MVVM] How to deal with fast changing properties In this article, I will describe a problem w ...

  3. ACM/ICPC 2018亚洲区预选赛北京赛站网络赛 A、Saving Tang Monk II 【状态搜索】

    任意门:http://hihocoder.com/problemset/problem/1828 Saving Tang Monk II 时间限制:1000ms 单点时限:1000ms 内存限制:25 ...

  4. 导出程序界面(UI)到图片

    无意间看到这个需求,查阅了相关文章,有两篇不错的博客给出了解决方案,地址如下: 1.在WPF程序中将控件所呈现的内容保存成图像 2.随心所欲导出你的 UI 界面到 PDF 文件 主要使用的接口: Si ...

  5. 随心所欲导出你的 UI 界面到 PDF 文件

    使用 C1PDF 控件可以导出文件到 PDF 文件,结合 .NET 平台特性你可以在任何客户端生成自定义报表.你可以打印任何 UI 界面,例如 DataGrid 导出到 PDF. 在本篇文章中我们将阐 ...

  6. TensorFlow 生成 .ckpt 和 .pb

    原文:https://www.cnblogs.com/nowornever-L/p/6991295.html 1. TensorFlow  生成的  .ckpt 和  .pb 都有什么用? The . ...

  7. Emacs及扩展配置

    Emacs及扩展配置 Table of Contents 1. 动机之反思 2. 它山之石 3. 扩展的管理 4. 我额外安装的通用扩展(在purcell基础上) 5. LaTex相关的问题和配置 6 ...

  8. 客户端类中中记录异常的方法: 使用Log4net

    1.首先引用Log4Net 的命名空间 using log4net; 2.在使用的类中生命静态变量 log public class FileService    {        static re ...

  9. COM Error Code(HRESULT)部分摘录

    Return value/code Description 0x00030200 STG_S_CONVERTED The underlying file was converted to compou ...

随机推荐

  1. 为什么axios请求接口会发起两次请求

    之前在使用axios发现每次调用接口都会有两个请求,第一个请求时option请求,而且看不到请求参数,当时也没注意,只当做是做了一次预请求,判断接口是否通畅,但是最近发现并不是那么回事. 首先我们知道 ...

  2. Redis常用操作及客户端工具

    修改redis密码 打开redis.windows.conf,找到requirepass  设置密码重启服务即可 将redis安装为windows服务,批处理如下: redis-server.exe ...

  3. 安装和卸载windows服务 bat

    1. 安装 windows服务 C:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil    [服务路径](例:C:\\test\myt ...

  4. VS2013全攻略

    http://blog.csdn.net/cpp12341234/article/details/45371269 挺好的,喜欢

  5. BUG-FREE-For Dream

    一直直到bug-free.不能错任何一点. 思路不清晰:刷两天. 做错了,刷一天. 直到bug-free.高亮,标红. 185,OA(YAMAXUN)--- (1) findFirstDuplicat ...

  6. Spring框架学习(一)

    一. spring概述 Spring 框架是一个分层架构,由 7 个定义良好的模块组成.Spring 模块构建在核心容器之上,核心容器定义了创建.配置和管理 bean 的方式,如图 1 所示. 图 1 ...

  7. struts-spring-mybatis实现最简单的登录验证

    1.导入项目相关的jar包 2.建立项目结构 3.配置文件的配置及代码 db.properties: jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:my ...

  8. ACM/ICPC 之 有流量上下界的网络流-Dinic(可做模板)(POJ2396)

    //有流量上下界的网络流 //Time:47Ms Memory:1788K #include<iostream> #include<cstring> #include<c ...

  9. caffe_实战之两个简单的例子(物体分类和人脸检测)

    一.物体分类: 这里使用的是caffe官网中自带的例子,我这里主要是对代码的解释~ 首先导入一些必要的库: import caffe import numpy as np import matplot ...

  10. [Sass]局部变量和全局变量

    [Sass]局部变量和全局变量 Sass 中变量的作用域在过去几年已经发生了一些改变.直到最近,规则集和其他范围内声明变量的作用域才默认为本地.如果已经存在同名的全局变量,从 3.4 版本开始,Sas ...