【问题标题】:In Xamarin.Forms, how to make image shrink to match container size在 Xamarin.Forms 中,如何使图像缩小以匹配容器大小
【发布时间】:2018-11-09 01:50:31
【问题描述】:

我有一个 Xamarin.Forms 应用程序,其页面显示图像和其他一些元素。图像是 png,在某些屏幕上它太大而无法在未缩放的同时显示所有其他元素。

我的问题是:有没有办法让 Xamarin.Forms 自动缩小图像以适应屏幕上的所有内容?

我有一个小例子来说明问题:

<?xml version="1.0" encoding="utf-8"?>
<ContentPage 
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
    xmlns:local="clr-namespace:PocImageScaling" 
    x:Class="PocImageScaling.MainPage">

    <StackLayout x:Name="stack1" BackgroundColor="Gray" Spacing="0">
        <BoxView x:Name="box1" HeightRequest="200" BackgroundColor="Yellow" />

        <Image x:Name="img1" Source="infoscreen_graphic.png" Aspect="AspectFit"/>

        <BoxView x:Name="box2" HeightRequest="200" BackgroundColor="Olive" />
        <BoxView x:Name="box3" HeightRequest="50" BackgroundColor="Yellow" />
    </StackLayout>
</ContentPage>

在代码隐藏中我有

    protected override void OnAppearing()
    {
        base.OnAppearing();

        Debug.WriteLine($"page.Height = {this.Height}");
        Debug.WriteLine($"stack1.Height = {stack1.Height}");
        Debug.WriteLine($"box1.Height = {box1.Height}");
        Debug.WriteLine($"img1.Height = {img1.Height}");
        Debug.WriteLine($"box2.Height = {box2.Height}");
        Debug.WriteLine($"box3.Y = {box3.Y}, box3.Height = {box3.Height}");
    }

我在 iPhone SE 的运行时看到的是

page.Height = 568
stack1.Height = 568
box1.Height = 200
img1.Height = 152
box2.Height = 200
box3.Y = 552, box3.Height = 50

黄色 box3 在底部几乎不可见,因此超出了 StackLayout 和 ContentPage 的范围。

我希望图像能够缩小到足以让所有内容都显示在屏幕上。

【问题讨论】:

    标签: xamarin xamarin.forms


    【解决方案1】:

    如果您希望图像缩放并且只占用可用空间,我会切换到 Grid 而不是 StackLayout

     <Grid x:Name="grid1" BackgroundColor="Gray" RowSpacing="0">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <BoxView x:Name="box1" HeightRequest="200" BackgroundColor="Yellow" />
        <Image Grid.Row="1" x:Name="img1" Source="AppIcon" Aspect="AspectFit" BackgroundColor="Pink"/>
        <BoxView Grid.Row="2" x:Name="box2" HeightRequest="200" BackgroundColor="Olive" />
        <BoxView Grid.Row="3" x:Name="box3" HeightRequest="50" BackgroundColor="Yellow" />
    </Grid>
    

    &lt;RowDefinition Height="Auto"/&gt; 将调整为您在该行中设置的视图HeightRequest,然后&lt;RowDefinition Height="*"/&gt; 将填充剩余的可用空间,这应该让所有内容都适合屏幕。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-19
      • 1970-01-01
      相关资源
      最近更新 更多