将Rect添加到画布

时间:2013-05-16 11:43:18

标签: c# wpf drawing

我正在尝试向Canvas添加Rect - 对象。使用Rectangle对象很容易。将它添加到Canvas。对于Rect来说,它似乎并不那么简单。在提供的链接上,我找到了以下代码来实现我想要的目标:

Path myPath1 = new Path();
myPath1.Stroke = Brushes.Black;
myPath1.StrokeThickness = 1;
SolidColorBrush mySolidColorBrush = new SolidColorBrush();
mySolidColorBrush.Color = Color.FromArgb(255, 204, 204, 255);
myPath1.Fill = mySolidColorBrush;

Rect myRect1 = new Rect();
myRect1.X = 10;
myRect1.Y = 100;
myRect1.Width = 150;
myRect1.Height = 100;
RectangleGeometry myRectangleGeometry1 = new RectangleGeometry();
myRectangleGeometry1.Rect = myRect1;

GeometryGroup myGeometryGroup1 = new GeometryGroup();
myGeometryGroup1.Children.Add(myRectangleGeometry1);

myPath1.Data = myGeometryGroup1;

// Add path shape to the UI.
Canvas myCanvas = new Canvas();
myCanvas.Children.Add(myPath1);
this.Content = myCanvas;

我无法相信我必须通过这一切来添加一个简单的Rect对象!当我想改变一个Rect(例如通过拖动)时,我必须再次完成这一切吗?必须有一个更简单的方法。我该怎么办?

编辑:我不使用System.Windows.Shapes对象,因为我无法计算是否存在某个Point(OnClick)。 System.Drawing.Rectangle可以做到这一点,但是它要求使用Rectangle而不是Point,即使文档另有说明......另外,您不能设置OpacityStroke属性,例如矩形。

1 个答案:

答案 0 :(得分:0)

为了确定是否单击了Rectangle,您可以向Rectangle对象本身添加MouseDownMouseLeftButtonDown处理程序:

<Canvas>
    <Rectangle Canvas.Left="100" Canvas.Top="100" Width="100" Height="100"
               Fill="AliceBlue" MouseLeftButtonDown="Rectangle_MouseLeftButtonDown"/>
</Canvas>

private void Rectangle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    var rect = sender as Rectangle;
    // do something
}

或在Canvas上调用InputHitTest并将返回的对象强制转换为Rectangle

<Canvas MouseLeftButtonDown="Canvas_MouseLeftButtonDown">
    <Rectangle Canvas.Left="100" Canvas.Top="100" Width="100" Height="100"
               Fill="Transparent" Stroke="Black" StrokeThickness="2"/>
</Canvas>

private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    var parent = sender as UIElement;
    var rect = parent.InputHitTest(e.GetPosition(parent)) as Rectangle;
    if (rect != null)
    {
        // do something
    }
}

当然,您可以在System.Windows.Shapes.Rectangle 上设置OpacityStroke等属性。