截取屏幕上指定区域
private void OnMenuExportGraph(object sender, RoutedEventArgs e)
{
if (_isLoaded == false)
{
MessageBox.Show("请先导入文件", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
else
{
int w = (int)this.Width;
int h = (int)this.Height;
// 自定义的处理方法
int imgWidth = (int)(...);
int imgHeight = (int)(...);
//Bitmap bit = new Bitmap(w, h);//实例化一个和窗体一样大的bitmap
Bitmap bit = new Bitmap(imgWidth, imgHeight);
Graphics g = Graphics.FromImage(bit);
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;//质量设为最高
g.CopyFromScreen((int)(this.Left+10), (int)(this.Top+65), (int)(0), (int)(0), new System.Drawing.Size(imgWidth, imgHeight));
// 指定存储位置
var dialog = new SaveFileDialog();
if (dialog.ShowDialog().GetValueOrDefault()) {
string filePath = dialog.FileName;
try
{
bit.Save(filePath);//默认保存格式为PNG,保存成jpg格式质量不是很好
MessageBox.Show("OK");
}
catch (Exception) {
MessageBox.Show("请检查存储位置", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
}
第一次写成这样:Bitmap bit = new Bitmap(w, h),导致打开时总有两条线在角落里。改变大小时,线段时有时无。后来发现是透明的背景,如下图。
把bit改小一些就可以了。
说明
CopyFromScreen函数的前两个参数是源矩形左上顶点的x和y坐标,随后是目标矩形左上顶点的x和y坐标,最后是实际截取的尺寸大小。创建Bitmap时,指定的是整张图片本身的大小(简称sizeA),而CopyFromScreen则指定了绘图区域的大小(简称sizeB)。由于窗口的大小会发生改变,所以:1.如果令sizeA=sizeB,那么为了避免截图区域受到干扰,必须小心调节源矩形左上顶点的坐标,这个我目前没有调整好;2.如果令sizeA为当前窗口的尺寸,那么源矩形左上顶点的坐标可以为定值,但是这样会出现上面那种透明背景问题;3.我实际需要截取的是这个区域里的Grid控件!!!这个控件我以后还会修改,所以不可能每次修改完之后都来调整坐标。因此,考虑使用截取控件本身的方法。
截取指定控件
public void OnMenuExportGraph(object sender, RoutedEventArgs e)
{
// 当前类的一个私有变量,可忽略
if (_isLoaded == false)
{
// 给出错误提示
MessageBox.Show("请先导入文件", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
else
{
int w = (int)this.Width;
int h = (int)this.Height;
// 自定义的处理方式
int imgWidth = ...;
int imgHeight = ...;
// 在自定义的控件对象 XXXControl 中 寻找名为 XXXXGrid 的Grid对象
// 这个函数我会写在另一篇日志里: https://blog.csdn.net/pxy7896/article/details/114317215
Grid grid = WpfTools.GetChildObject<Grid>(this.XXXControl, "XXXXGrid");
RenderTargetBitmap targetBitmap = new RenderTargetBitmap((int)imgWidth, (int)imgHeight, 96d, 96d, PixelFormats.Default);
targetBitmap.Render(grid);
PngBitmapEncoder saveEncoder = new PngBitmapEncoder();
saveEncoder.Frames.Add(BitmapFrame.Create(targetBitmap));
// 指定存储位置
var dialog = new SaveFileDialog();
// 指定后缀
dialog.Filter = "PNG图片|*.png";
if (dialog.ShowDialog().GetValueOrDefault()) {
string filePath = dialog.FileName;
try
{
// 保存文件
System.IO.FileStream fs = System.IO.File.Open(filePath, System.IO.FileMode.OpenOrCreate);
saveEncoder.Save(fs);
fs.Close();
MessageBox.Show("导出成功");
}
catch (Exception) {
MessageBox.Show("请检查存储位置", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
}
这样就能保存grid本身了,也正是我实际需要截取的对象。