如何将 WPF 图像 + 形状刻录到新图像



我有一个带有画布的 WPF 用户控件。 它大致看起来像这样(底部有更完整的版本(:

<UserControl>
<Canvas>
<Image x:Name="CurrentImage" ... etc .../>
<Path x:Name="SurfacePath" ... etc .../>
</Canvas>
</UserControl>

在屏幕上看起来很棒,但我需要编写代码,从所有这些中创建与原始图像大小相同的新图像"蒙版"。此蒙版将表示两者的组合,原始图像像素为黑色,而叠加的形状像素为白色。 (低级 SDK 稍后将使用像素数据进行一些繁重的数学运算。

不幸的是,我不知道如何创建这个"面具"图像。 除了在面板中布置元素和使用几何图形构建路径之外,WPF 绘图的实际工作方式一直让我感到困惑。 我迷失在所有具有相似名称的类中,以及何时使用它们,图像绘图与绘图图像等。 我已经在这里阅读,谷歌和搜索了很多,但我仍然不知道从哪里开始。

谁能给我一个粗略的轮廓,我将采取哪些步骤来解决这个问题?

这是我正在使用的更完整的版本。

<UserControl x:Class="MyProject.Core.Shapes.ShapeCanvas"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
UseLayoutRounding="true"
>
<Canvas x:Name="Scene">
<!--Image is drawn first, underneath everything else.  Image 0,0 is Canvas 0,0-->
<Image x:Name="CurrentImage" 
Canvas.Left="0" Canvas.Top="0"
Source="{Binding Image, Mode=OneWay}"/>
<!-- Path showing the current polyline created with the "Surface" tool. -->
<Path x:Name="SurfacePath"
ClipToBounds="False"
Canvas.Left="0"
Canvas.Top="0"
Stroke="Gray"
StrokeThickness="50" 
>
<Path.Data>
<PathGeometry>
<PathGeometry.Figures>
<PathFigure StartPoint="{Binding CurrentSegmentStartPoint}">
<PathFigure.Segments>
<PolyBezierSegment Points="{Binding CurrentSegmentPoints}"/>
</PathFigure.Segments>
</PathFigure>
</PathGeometry.Figures>
</PathGeometry>
</Path.Data>
</Path>
</Canvas>
</UserControl>

我已使用此代码将 WPF 控件呈现为用于代码隐藏的位图源/图像:

public static BitmapSource Create(UIElement control, Size size = default(Size))
{
if (control == null)
return null;
if (size == Size.Empty || (size.Height == 0 && size.Width == 0))
size = new Size(double.PositiveInfinity, double.PositiveInfinity);
control.Measure(size);
RenderTargetBitmap bmp = new RenderTargetBitmap((int)control.DesiredSize.Width, (int)control.DesiredSize.Height, 96, 96, PixelFormats.Pbgra32);
Rect rect = new Rect(0, 0, control.DesiredSize.Width, control.DesiredSize.Height);
control.Arrange(rect);
control.UpdateLayout();
bmp.Render(control);
bmp.Freeze();
return bmp;
}

它是这里答案的衍生物:https://stackoverflow.com/a/27077188/8302901

如果控件是屏幕上已有控件的实例,请跳过度量、排列和布局步骤,仅使用已计算的大小。

最新更新