![](/img/trans.png)
[英]Scale Image in NavigationItem.TitleView to fit inside of the UINavigationBar
[英]How to scale image to fit 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”,但它沒有改變任何東西。
我不知道為什么,但我發現了這個。 我創建了一個這樣的轉換器:
class dblMultiplier : IValueConverter, IMarkupExtension
{
public double Multiplier { get; set; } = 1.0f;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return System.Convert.ToDouble(value) * 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 Multiplier=0.99}}"/>
轉換器被調用兩次。 當標簽的高度尚未固定時,默認值為 -1。 計算布局時的第二個。 所以它完美地工作。
但是如果我使用 1.0 而不是 0.99 的相同轉換器,它就不起作用!!! 圖像的大小不適應......?!? 很奇怪吧?
好的,我找到了核心問題...
(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 的整個高度。 否則不會發生縮放。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.