Xamarin Forms图像控件分配的高度超出了要求

时间:2019-04-09 16:19:35

标签: c# .net xaml xamarin xamarin.forms

我正在将HeightRequest的显式16设置为我的Image元素;但是,在调试时,实际的Height似乎跳到了70。这是我的Xaml:

<Grid Margin="1" Padding="0" ColumnSpacing="0" RowSpacing="0" HeightRequest="17">
    <BoxView CornerRadius="3" Color="LightGray"/>
    <BoxView Margin="1" CornerRadius="3" BackgroundColor="White"/>
    <StackLayout Margin="2,0,2,0" Orientation="Horizontal" HeightRequest="17" Spacing="0">
        <Image Source="hooray_icon"
               WidthRequest="16"
               HeightRequest="16"
               Margin="1,0,1,0"
               Aspect="Fill"/>
        <Label Text="{Binding HoorayCount}"
               Margin="1,0,1,0"
               VerticalOptions="Center"
               VerticalTextAlignment="Center"
               HorizontalOptions="Center"
               HorizontalTextAlignment="Center"
               HeightRequest="16"/>
    </StackLayout>
</Grid>

预期设计:

Expected

实际设计:

Actual

hooray_icon是512x512的PNG图片。

Xamarin.Forms版本:3.6.0.293080

PS我知道是Image元素通过使用class CustomImage : Image并重写和调试OnMeasureOnSizeAllocated方法导致了问题。如果我弄错了,请纠正我。

1 个答案:

答案 0 :(得分:0)

答案

HeightRequest不能保证,它只是一个请求。如果Xamarin.Forms能够满足请求,它将实现该请求,但是根据屏幕大小和布局,它可能无法满足该请求。

解决方案

设置Grid.ColumnDefinition's Width and the Grid.RowDefinition's Height的值。

代码

<Grid Margin="1" Padding="0" ColumnSpacing="0" RowSpacing="0">
  <Grid.RowDefinitions>
    <RowDefinition Height="17" />
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="17" />
    <ColumnDefinition Width="17" />
    <ColumnDefinition Width="17" />
  </Grid.ColumnDefinitions>
    <BoxView CornerRadius="3" Color="LightGray" Grid.Row="0" Grid.Column="0"/>
    <BoxView Margin="1" CornerRadius="3" BackgroundColor="White" Grid.Row="0" Grid.Column="1"/>
    <StackLayout Margin="2,0,2,0" Orientation="Horizontal" Spacing="0" Grid.Row="0" Grid.Column="2">
        <Image Source="hooray_icon"
               Margin="1,0,1,0"
               Aspect="Fill"
               HeightRequest="16"/>
        <Label Text="{Binding HoorayCount}"
               Margin="1,0,1,0"
               VerticalOptions="Center"
               VerticalTextAlignment="Center"
               HorizontalOptions="Center"
               HorizontalTextAlignment="Center"
               HeightRequest="16"/>
    </StackLayout>
</Grid>