如何允许用户在Silverlight 3.0 App中绘制自由形式的矩形

时间:2010-01-02 15:56:16

标签: silverlight silverlight-3.0

功能:用户可以在屏幕的指定区域绘制矩形,方法是单击鼠标左键并拖动以创建所需大小的矩形。类似的例子是在BLEND中重新调整矩形的大小。我也对矩形已存在的选项持开放态度,用户可以使用拖动/调整大小手柄来调整大小。

关于如何实现这一目标的想法?

1 个答案:

答案 0 :(得分:1)

可以非常轻松地在画布上绘制矩形: -

 <Canvas x:Name="draw" Background="Transparent" MouseLeftButtonDown="draw_MouseLeftButtonDown" />

那么: -

    Point origPoint; 
    Rectangle rect;
    void draw_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        rect = new Rectangle();
        origPoint = e.GetPosition(draw);
        Canvas.SetLeft(rect, origPoint.X);
        Canvas.SetTop(rect, origPoint.Y);
        rect.Stroke = new SolidColorBrush(Colors.Black);
        rect.StrokeThickness = 2;

        draw.Children.Add(rect);

        draw.MouseMove += draw_MouseMove;
        draw.MouseLeftButtonUp += draw_MouseLeftButtonUp;
    }

    void draw_MouseMove(object sender, MouseEventArgs e)
    {
        if (rect != null)
        {
            Point curPoint = e.GetPosition(draw);
            if (curPoint.X > origPoint.X)
            {
                rect.Width = curPoint.X - origPoint.X;
            }
            else if (curPoint.X < origPoint.X)
            {
                Canvas.SetLeft(rect, curPoint.X);
                rect.Width = origPoint.X - curPoint.X;
            }

            if (curPoint.Y > origPoint.Y)
            {
                rect.Height = curPoint.Y - origPoint.Y;
            }
            else if (curPoint.Y < origPoint.Y)
            {
                Canvas.SetTop(rect, curPoint.Y);
                rect.Height = origPoint.Y - curPoint.Y;
            }
        }

    }

    void draw_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        if (rect != null)
        {
            draw.MouseMove -= draw_MouseMove;
            draw.MouseLeftButtonUp -= draw_MouseLeftButtonUp;
            rect = null;
        }
    }

这是否真的可以满足您的要求我不确定。它实际上取决于画布下面可能包含的内容以及绘制后矩形的用途。