如何缩放图像而不让它占据未缩放图像的整个宽度/高度?在这个简单的示例中,我希望图像的宽度和高度是其所在容器的 25%。
<AbsoluteLayout>
<Image
AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="0, 0, .25, .25"
Source="{Binding NiceImage}" />
</AbsoluteLayout>
这确实缩放了图像,但图像仍然占用与未缩放图像相同的空间量。 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。
我在这里发布了一个示例:
关于xamarin - 在 Xamarin 中,如何缩放图像而不使其占用与未缩放时相同的空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51621674/