xamarin - 在 Xamarin 中,如何缩放图像而不使其占用与未缩放时相同的空间?

标签 xamarin xamarin.forms

如何缩放图像而不让它占据未缩放图像的整个宽度/高度?在这个简单的示例中,我希望图像的宽度和高度是其所在容器的 25%。

<AbsoluteLayout>
       <Image
           AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="0, 0, .25, .25"
           Source="{Binding NiceImage}" />
</AbsoluteLayout>

enter image description here

这确实缩放了图像,但图像仍然占用与未缩放图像相同的空间量。 Aspect 似乎不适用于此。

最佳答案

您可以将图像的 WidthRequest 绑定(bind)到父容器的 WidthRequest,但使用值转换器进行缩放。

如果您创建一个如下所示的值转换器:

public class CoefConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        double coef = 1.0;

        if (parameter is string)
            coef = double.Parse(parameter as string);

        return (double)value * coef;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

您可以在标记中使用它,如下所示:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:ScaleImage"
             x:Class="ScaleImage.MainPage">

    <ContentPage.Resources>
        <ResourceDictionary>
            <local:CoefConverter x:Key="cc" />
        </ResourceDictionary>
    </ContentPage.Resources>

    <StackLayout x:Name="theStack">

        <Image Source="mountain.jpg" Aspect="AspectFit" HorizontalOptions="Start" 
               WidthRequest="{Binding Source={x:Reference theStack}, Path=Width, Converter={StaticResource cc}, ConverterParameter=0.25}"  />
        <Label Text="This is some text!" FontSize="Medium" />

    </StackLayout>

</ContentPage>

本质上,您将 Image 的 WidthRequest 设置为父级(名为 theStack)的 WidthRequest,但乘以 0.25。

我在这里发布了一个示例:

https://github.com/curtisshipley/ScaleImageConverter

关于xamarin - 在 Xamarin 中,如何缩放图像而不使其占用与未缩放时相同的空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51621674/

相关文章:

android - Xamarin Forms - IOS - 汉堡包菜单标题颜色与状态栏不同

xamarin - MAUI CarouselView : how to imitate swipe effect in code? 滑动动画不会发生

java - Xamarin - 我应该使用哪些 NDK 版本?

android - 如何在 Visual Studio Community 2015 中更新 Xamarin for Android

ios - 在 Xamarin 中使用 transitionWithView 设置 UIView.Hidden 属性时淡入淡出动画

c# - OneSignal:如何处理在 Xamarin.Forms 应用程序的 AppDelegate 中打开的通知?

xamarin - 如何防止键盘打开时背景图像被挤压?

c# - 更新单个属性集的多个属性

c# - MvxCachingFragmentCompatActivity 刷新缓存 fragment

c# - Xamarin Plugin.Geolocator 不工作