使用句柄在Silverlight中调整大小

时间:2011-01-15 21:15:26

标签: silverlight

我有一个图像和一个手柄。我想用两种效果拖动手柄:调整图片大小并移动手柄以使其保持在图片的角落。这是我的代码:

    public void StartResizing(object sender, MouseEventArgs e)
    {
        resizing = true;

        Point pos = e.GetPosition(null);
        resizeX = pos.X;
        resizeY = pos.Y;
        distH = pos.X - 200; //Canvas.Left of the image
        distV = pos.Y - 50; //Canvas.Top of the image
    }

    public void KeepResizing(object sender, MouseEventArgs e)
    {
        if (resizing)
        {
            Point p = e.GetPosition(null);
            double x = p.X - resizeX;
            double y = p.Y - resizeY;

            this.handle.SetValue(Canvas.LeftProperty, 280 + x); //280.130 is the original position of the handle
            this.handle.SetValue(Canvas.TopProperty, 130 + y);

            double newDistH = p.X - 200;
            double newDistV = p.Y - 50;
            pic2.Height = (newDistV / distV) * orgHeight; //orgHeight and Widthinitialised earlier
            pic2.Width  = (newDistH / distH) * orgWidth;
        }
    }

    public void StopResizing(object sender, MouseEventArgs e)
    {
        resizing = false;
    }

它可以正常工作,直到我第二次尝试调整它的大小。那时图像通常以看似随机的方式缩小。代码有什么问题?

1 个答案:

答案 0 :(得分:4)

首先要做的是让Silverlight为您完成更多工作。考虑一下这个Xaml: -

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>
        <Image x:Name="image" Source="someUrl" Width="200" Height="200" Margin="0 0 8 8" />
        <Rectangle x:Name="handle" VerticalAlignment="Bottom" HorizontalAlignment="Right" Fill="Blue" Width="8" Height="8" MouseLeftButtonDown="handle_MouseLeftButtonDown" />
    </Grid>

现在在代码中你只需要调整图像大小,Grid控件将查看大小调整手柄的位置。以下是管理图像大小的handle_MouseLeftButtonDown的代码: -

    private void handle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        UIElement handle = (UIElement)sender;

        Point origMouse = e.GetPosition(null);
        Size origSize = new Size(image.Width, image.Height);
        handle.CaptureMouse();

        MouseEventHandler mouseMove = (s, args) =>
        {
            Point p = args.GetPosition(null);
            image.Width = Math.Max(0.0, origSize.Width + p.X - origMouse.X);
            image.Height = Math.Max(0.0, origSize.Height + p.Y - origMouse.Y);
        };
        handle.MouseMove += mouseMove;

        MouseButtonEventHandler mouseUp = null;
        mouseUp = (s, args) =>
        {
            handle.ReleaseMouseCapture();
            handle.MouseMove -= mouseMove;
            handle.MouseLeftButtonUp -= mouseUp;
        };
        handle.MouseLeftButtonUp += mouseUp;
    }