开发者

How to allow users to draw freeform rectangles in Silverlight 3.0 App

The functionality: Users can draw rectangles on a defined area of the screen开发者_JS百科, by clicking the left mouse button and dragging to create the desired sized rectangle. A similar example would be re-sizing a rectangle in BLEND. I am also open to options where the rectangle already exists, and users can resize using a drag/resize handle.

Ideas on how this might be accomplished?


Drawing rectangles on to a canvas can be done fairly easily:-

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

then:-

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

Whether this can actually full fill your requirements I'm not sure. It would really depend on what you might have underneath the canvas and what you wanted to do with the rectangles once drawn.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜