如何使用 MVVM 模式在 Xamarin 中缩放 ListView 中的图像?

问题描述 投票:0回答:1

我是 Xamarin 的新手,特别是 MVVM 的新手。我有一个

ListView
,它正在向我显示图像。

<ListView ItemsSource="{Binding Urls}" IsVisible="True" VerticalScrollBarVisibility="Always" HorizontalScrollBarVisibility="Always" HorizontalOptions="Fill" VerticalOptions="Fill" HasUnevenRows="True">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Orientation="Vertical" HorizontalOptions="Fill" VerticalOptions="FillAndExpand" Padding="2">
                    <ffimageloading:CachedImage Source="{Binding .}" Aspect="AspectFill" Margin="15">
                        <ffimageloading:CachedImage.GestureRecognizers>                                        
                            <TapGestureRecognizer Command="{Binding Source={x:Reference ImgListView},Path=BindingContext.ImageDoubleTappedCommand}" />
                        </ffimageloading:CachedImage.GestureRecognizers>
                    </ffimageloading:CachedImage>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

现在我想要通过双击和捏合进行缩放的缩放行为。 我在互联网上找到了不同的链接,但这些链接没有实现 MVVM。 例如:https://www.c-sharpcorner.com/article/zoom-in/。 如何在 MVVM 中获得缩放功能?

c# image xamarin mvvm
1个回答
0
投票

我只是使用后面的代码来触发事件并使用那里的缩放逻辑:

<TapGestureRecognizer Tapped="TapGestureRecognizer_TappedAsync" />

以下逻辑来自链接:https://www.c-sharpcorner.com/article/zoom-in/

double currentScale = 1;
double startScale = 1;
double xOffset = 0;
double yOffset = 0;
private void TapGestureRecognizer_TappedAsync(object sender, System.EventArgs e)
{
    var Content = ((FFImageLoading.Forms.CachedImage)sender);

    double multiplicator = Math.Pow(2, 1.0 / 10.0);
    startScale = Content.Scale;
    Content.AnchorX = 0;
    Content.AnchorY = 0;

    for (int i = 0; i < 10; i++)
    {
        currentScale *= multiplicator;
        double renderedX = Content.X + xOffset;
        double deltaX = renderedX / Content.Width;
        double deltaWidth = Content.Width / (Content.Width * startScale);
        double originX = (0.5 - deltaX) * deltaWidth;

        double renderedY = Content.Y + yOffset;
        double deltaY = renderedY / Content.Height;
        double deltaHeight = Content.Height / (Content.Height * startScale);
        double originY = (0.5 - deltaY) * deltaHeight;

        double targetX = xOffset - (originX * Content.Width) * (currentScale - startScale);
        double targetY = yOffset - (originY * Content.Height) * (currentScale - startScale);

        Content.TranslationX = Math.Min(0, Math.Max(targetX, -Content.Width * (currentScale - 1)));
        Content.TranslationY = Math.Min(0, Math.Max(targetY, -Content.Height * (currentScale - 1)));

        Content.Scale = currentScale;
        //await Task.Delay(10);
    }

    xOffset = Content.TranslationX;
    yOffset = Content.TranslationY;
}
© www.soinside.com 2019 - 2024. All rights reserved.