0

现在,我正在开发照片应用程序(windows phone 8.1 runtime),但我遇到的问题是在照片缩放时没有限制图像拖动区域。

在此处输入图像描述

下面是代码:

<Canvas Name="zoomgrid" Visibility="Collapsed">
    <Image x:Name="zoomimages"
           Stretch="Fill"
           Width="480"
           Height="800"
           ManipulationDelta="img_intro_ManipulationDelta"
           RenderTransformOrigin="0.5,0.5"
           ManipulationMode="All">
        <Image.RenderTransform>
            <CompositeTransform/>
        </Image.RenderTransform>                
    </Image>
</Canvas>

double mincale = 0.5;
double maxscale = 10.0;

private void Image_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{           
    Image elemt = sender as Image;
    CompositeTransform transform = elemt.RenderTransform as CompositeTransform;

    transform.ScaleX *= e.Delta.Scale;
    transform.ScaleY *= e.Delta.Scale;

    transform.TranslateX += e.Delta.Translation.X;
    transform.TranslateY += e.Delta.Translation.Y;

    if (transform.ScaleX < mincale) transform.ScaleX = mincale;
    if (transform.ScaleY < mincale) transform.ScaleY = mincale;
    if (transform.ScaleX > maxscale) transform.ScaleX = maxscale;
    if (transform.ScaleY > maxscale) transform.ScaleY = maxscale;

    //To limit the images dragging but did not success.
    double scalewidth = Zoomimages.ActualWidth * ct.ScaleX;
    double scleheight = Zoomimages.ActualHeight * ct.ScaleY;

    double xdiff = Math.Max(0, (scalewidth - this.content.ActualWidth) / 2);
    double ydiff = Math.Max(0, (scleheight - this.content.ActualHeight) / 2);

    if (Math.Abs(ct.TranslateX) > xdiff)
        ct.TranslateX = xdiff * Math.Sign(e.Delta.Translation.X);
    if (Math.Abs(ct.TranslateY) > ydiff)
        ct.TranslateY = ydiff * Math.Sign(e.Delta.Translation.Y);             
}
4

1 回答 1

0

我通过使用辅助方法来检查图像当前是否在另一个元素的范围内来实现这一点。

在您的情况下,您要检查的元素是图像,并且您要检查它是否在画布的范围内。

private bool IsElementVisible(FrameworkElement element, FrameworkElement container)
    {
        if (!element.IsVisible)
            return false;

        Rect bounds = element.TransformToAncestor(container).TransformBounds(new Rect(0.0, 0.0, element.ActualWidth, element.ActualHeight));
        Rect rect = new Rect(0.0, 0.0, container.ActualWidth, container.ActualHeight);

        if (rect.Left > bounds.Right || rect.Right < bounds.Left || rect.Bottom < bounds.Top || rect.Top > bounds.Bottom)
        {
            return false;
        }

        return true;
    }

在我的例子中,我使用了 MatrixTransform 而不是 CompositeTransform,但方法应该是相同的。

我通常为“ManipulationStarting”和“ManipulationCompleted”创建处理程序,其中:

操作开始:

  1. 存储变换的当前(操作前)副本。

操作完成:

  1. 检查图像是否超出范围(使用我发布的方法)。
  2. 如果超出范围,则恢复为原始变换。

这样,即使您的图像被拖出视图 - 只要用户抬起手指,图像就会弹回最后的正确位置。

如果您对我使用此代码的更广泛的上下文感兴趣,我有一个封装所有这些功能的 WPF 行为。代码在Codeplex 上。这门课你可能会感兴趣。

我希望这有帮助 :)

于 2014-12-02T12:12:04.110 回答