WPF自定义画布无法正确重绘位图
我已经实现了一个类似于WPF DrawTools的自定义画布。通过将画布转换为位图,执行整体填充算法,然后将位图写回画布,我实现了整体填充工具 我遇到的问题是画布重新绘制不正确。画布保持在相对于窗口的正确位置,但画布中的图形将根据偏移量进行移动。以下是执行转换的相关代码:WPF自定义画布无法正确重绘位图,wpf,canvas,Wpf,Canvas,我已经实现了一个类似于WPF DrawTools的自定义画布。通过将画布转换为位图,执行整体填充算法,然后将位图写回画布,我实现了整体填充工具 我遇到的问题是画布重新绘制不正确。画布保持在相对于窗口的正确位置,但画布中的图形将根据偏移量进行移动。以下是执行转换的相关代码: public static WriteableBitmap GetBitmap(CCDrawingCanvas canvas) { // Local variables double d
public static WriteableBitmap GetBitmap(CCDrawingCanvas canvas) {
// Local variables
double dpi = 96d;
// Get the size of the canvas
System.Windows.Size size = new System.Windows.Size((int)canvas.ActualWidth, (int)canvas.ActualHeight);
// Measure and arrange the surface
Point relativePoint = canvas.TransformToAncestor(Application.Current.MainWindow)
.Transform(new Point(0, 0));
canvas.Measure(size);
canvas.Arrange(new Rect(size));
RenderTargetBitmap source = new RenderTargetBitmap(
(int)canvas.ActualWidth,
(int)canvas.ActualHeight,
dpi,
dpi,
PixelFormats.Pbgra32);
canvas.RenderTransform = new TranslateTransform(relativePoint.X, relativePoint.Y);
source.Render(canvas);
return new WriteableBitmap(source);
}
绘制第一条线时,画布和图形将正确渲染。之后添加的每一行新行都会将画布的每个子元素向下移动relativePoint.Y,然后再移动relativePoint.X
如果移除relativePoint变换并返回WriteableBitmap,画布将在相对于整个窗口的位置0,0处绘制。这会由于与此位置的其他控制元素重叠而导致问题
我已经包括了两幅图像,显示了第一条线绘制后的位置和第二条线绘制后的位置
在画布元素的最顶端绘制的第一行。
第二条线是在画布的最顶端绘制的,但重画会将其向下移动相对点Y
更新日期:2014年5月4日:我发现了一个临时解决方案。通过首先获取视觉元素相对于窗口的位置,然后根据0,0位置排列画布,可以更改此过程。调用RenderTargetBitmap.Render方法后,画布将再次相对于存储点进行排列。这是更新后的代码。我仍然想知道如何更优雅地执行此操作,因为此修复程序相当松散
public static WriteableBitmap GetBitmap(CCDrawingCanvas canvas) {
// Local variables
double dpi = 96d;
// Get the size of the canvas
System.Windows.Size size = new System.Windows.Size((int)canvas.ActualWidth, (int)canvas.ActualHeight);
// Measure and arrange the surface based at a location of (0, 0) to write the bitmap properly
canvas.Measure(size);
Point relativePoint = canvas.TransformToAncestor(Application.Current.MainWindow)
.Transform(new Point(0, 0));
canvas.Arrange(new Rect(size));
RenderTargetBitmap source = new RenderTargetBitmap(
(int)canvas.Width,
(int)canvas.Height,
dpi,
dpi,
PixelFormats.Pbgra32);
source.Render(canvas);
// Arrange the canvas back to its original position.
canvas.Arrange(new Rect(relativePoint, size));
return new WriteableBitmap(source);
}
这里没有答案,我也在寻找解决方案。这样