gpt4 book ai didi

c# - 如何获取 "visible"大小的 Canvas ?

转载 作者:行者123 更新时间:2023-12-04 07:40:53 27 4
gpt4 key购买 nike

我需要将 Canvas 的可见内容保存为 PNG。

我有以下方法获取 Canvas 的实际大小并将其保存为图像。

        private void SavePng()
{
Rect bounds = VisualTreeHelper.GetDescendantBounds(this.CanvasMain);

//I also tried this
/*Rect bounds = new Rect(
new Point(0, 0),
new Point(this.CanvasMain.ActualWidth, this.CanvasMain.ActualHeight)
);*/

double dpi = 96d;

RenderTargetBitmap rtb = new RenderTargetBitmap((int)bounds.Width, (int)bounds.Height, dpi, dpi, System.Windows.Media.PixelFormats.Default);

DrawingVisual dv = new DrawingVisual();
using (DrawingContext dc = dv.RenderOpen())
{
VisualBrush vb = new VisualBrush(this.CanvasMain);
dc.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
}

rtb.Render(dv);

BitmapEncoder pngEncoder = new PngBitmapEncoder();
pngEncoder.Frames.Add(BitmapFrame.Create(rtb));

try
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();

pngEncoder.Save(ms);
ms.Close();

SaveFileDialog dlg = new SaveFileDialog();
dlg.DefaultExt = ".png";
dlg.Filter = "Image (.png)|*.png";
string filename = "";
if (dlg.ShowDialog() == true)
filename = dlg.FileName;

System.IO.File.WriteAllBytes(filename, ms.ToArray());
}
catch (ArgumentException err)
{
MessageBox.Show("Wrong path!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}

但是如果我有一个超出窗口范围的对象,我会得到这样的结果:

Canvas is a gray part.

如何只获取窗口边界内 Canvas 的可见部分?

最佳答案

VisualBrush 自动确定其“渲染内容”的边界。

为了避免这种情况,设置它的 Viewbox 属性:

var rect = new Rect(CanvasMain.RenderSize);

var rtb = new RenderTargetBitmap(
(int)rect.Width, (int)rect.Height, 96, 96, PixelFormats.Default);

var dv = new DrawingVisual();

using (var dc = dv.RenderOpen())
{
var vb = new VisualBrush
{
Visual = CanvasMain,
Viewbox = rect,
ViewboxUnits = BrushMappingMode.Absolute
};

dc.DrawRectangle(vb, null, rect);
}

rtb.Render(dv);

或者,将 Canvas 的 ClipToBounds 属性设置为 true:

<Canvas x:Name="CanvasMain" ClipToBounds="True" ...>

关于c# - 如何获取 "visible"大小的 Canvas ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67472818/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com