0

我正在尝试将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 对象!当我想改变一个矩形(例如通过拖动)时,我必须再次经历这一切吗?必须有更简单的方法。我应该怎么办?

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

4

1 回答 1

0

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

<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
}

或调用InputHitTestCanvas 并将返回的对象转换为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 Opacity之类Stroke的属性。

于 2013-05-16T11:59:05.290 回答