首页 > 解决方案 > 如何缩放图像以适合 TitleView

问题描述

我使用 TitleView 布局在导航栏中使用图像。它有效,但......

我遇到了根据导航栏的高度设置图像大小的问题。

<NavigationPage.TitleView>
    <StackLayout Orientation="Horizontal"
                 VerticalOptions="Center"
                 Spacing="10">

        <Image Source="flechegauche.png" BindingContext="{x:Reference TitleLabel}" HeightRequest="{Binding Height}"/>

        <Label x:Name="TitleLabel" Text="Evènements" FontSize="16" TextColor="White" 
               VerticalTextAlignment="Center" VerticalOptions="FillAndExpand"
               HorizontalTextAlignment="Center" HorizontalOptions="FillAndExpand" />

        <Image Source="filtre.png" HeightRequest="{OnPlatform iOS=60, Android=35, Default=40}"/>
        <Image Source="flechedroite.png" HeightRequest="{OnPlatform iOS=60, Android=35, Default=40}"/>

    </StackLayout>
</NavigationPage.TitleView>

如果我使用它可以工作:HeightRequest="{OnPlatform iOS=60, Android=35, Default=40}"

但这不起作用: BindingContext="{x:Reference TitleLabel}" HeightRequest="{Binding Height}"

为什么 ?!?它仍然是将图像高度链接到导航栏高度的最佳方法(以确保图像正确适合),不是吗?

我也尝试将“Aspect”设置为“AspectFit”,但它并没有改变任何东西。

标签: c#xamarin.formsnavigationbar

解决方案


好的,我找到了核心问题...

(1)我的图像在第一次出现时(布局计算之前)太大,所以没有显示用于缩放图像的标签,因此标签不能用于缩放图像,并且图像不显示预期的大小!

所以,我做了一个转换器,在开始时强制使用一个小的默认值:

class dblMultiplier : IValueConverter, IMarkupExtension
{
    public double Multiplier { get; set; } = 1.0f;
    public double Default { get; set; } = double.NaN;

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        double dvalue = System.Convert.ToDouble(value);

        if (dvalue < 0.0f && !double.IsNaN(Default) )
            return Default;

        return dvalue * Multiplier;
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException("Only one way bindings are supported with this converter");
    }

    public object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }
}

我像这样更改了 XAML:

<Image Source="flechegauche.png" HeightRequest="{Binding Source={x:Reference TitleLabel}, Path=Height, Converter={Helpers:dblMultiplier Default=10}}"/>

(2) 我还必须确保标签不适合 TitleView 的整个高度。否则不会发生缩放。


推荐阅读