“堆叠”画布元素

时间:2019-12-13 08:32:57

标签: c# wpf xaml

因此,我制作了一个基本上在图像上绘制形状和文本的应用程序。为此,我使用了画布(从现在开始将其称为imageCanvas),并且一切正常。但是,我需要添加一个在图像和imageCanvas上绘制(并通过复选框隐藏/显示)网格线的函数。因此,我制作了一个名为boxCanvas的新画布,并将其放在imageCanvas的顶部。

我使用了两个视图框,因为它们需要可伸缩,但是问题是当我尝试通过代码在第二个画布上添加元素时,网格线将不会显示。

// XAML
<Viewbox HorizontalAlignment="Center" Grid.Column="0" Grid.ColumnSpan="9" Grid.Row="5">
    <Canvas x:Name="imageCanvas">
    </Canvas>
</Viewbox>

<Viewbox HorizontalAlignment="Center" Grid.Column="0" Grid.ColumnSpan="9" Grid.Row="5">
    <Canvas x:Name="boxCanvas">
    </Canvas>
</Viewbox>

// CODE-BEHIND
// I had to cut the entire code because it's too long, but here's the gist:
// 1. Set the image
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(imagePath);
bitmap.EndInit();
detectedImage.Source = bitmap;

// 2. Draw shapes and text
var rect = new Rectangle
{
    StrokeThickness = 3 * lineWidth,
    Stroke = new SolidColorBrush(SetColor),
    Width = x.width,
    Height = x.height
};
Canvas.SetLeft(rect, x.left);
Canvas.SetTop(rect, x.top);
ca.Children.Add(rect);

var text = new TextBlock
{
    Foreground = new SolidColorBrush(Colors.White),
    Text = "ID:" + inc,
    FontSize = 12 * lineWidth
};
Canvas.SetLeft(text, (double)x.left);
Canvas.SetTop(text, (double)x.top - text.FontSize - 4);
ca.Children.Add(text);

// 3. Draw grid lines
private void DrawLines(BitmapImage image, int strideX, int strideY, int unitX, int unitY)
{
    var rect = new Rectangle
        {
            StrokeThickness = 4,
            Stroke = new SolidColorBrush(Colors.Aqua),
            Width = unitX,
            Height = unitY
        };
        Canvas.SetLeft(rect, ox);
        Canvas.SetTop(rect, oy);
        boxCanvas.Children.Add(rect);
}

知道为什么会这样吗?

1 个答案:

答案 0 :(得分:0)

对不起,我知道了。我只是忘了在后面的代码中设置画布的宽度和高度。

谢谢!