在 nativescript 的绝对布局中心定位元素

position element at center of absolute layout in nativescript

我有一个来自 api 的对象列表,我在 ListView 中显示了这些对象。对于列表中的每个项目,我正在渲染一个绝对布局。如果该项目有照片,我会显示它完全拉伸,以便它在列表中显示为该项目的背景图像。然后我正在渲染带有项目名称的按钮,我想在图像的中心渲染它。我浏览了文档,但找不到方法。

<ListView [items]="List">
  <StackLayout>
    <template let-item="item">
      <AbsoluteLayout  class="list-item">
        <Image src="{{item.photo}}" *ngIf="item.photo" stretch="fill">  </Image>
        <Button [text]="item.name" (tap)="onItemTap(item)"></Button>
      </AbsoluteLayout>
    </template>
  </StackLayout>    
</ListView>

您可以为 AbsoluteLayout 中的组件设置 lefttop。 现在,如果您有相同大小的图像,事情就很简单了——您可以根据缩略图大小提供从左侧和顶部的位移。或者您可以根据代码隐藏计算和更多绑定提供左侧和顶部位移 例如

  <AbsoluteLayout>
    <Image src="{{item.photo}}" *ngIf="item.photo" stretch="fill">  </Image>
    <Button text="This is Label 1" [left]="leftValueBasedOnImageSize" [top]="topValueBasedOnImageSize" ></Button>
  </AbsoluteLayout>

您还可以设置绝对布局的大小,并根据该尺寸将按钮置于中心。

  <AbsoluteLayout width="300" height="300">
    <Image src="{{item.photo}}" left="0" top="0" width="300" height="300" stretch="aspectFill">  </Image>
    <Button text="Button" left="120" top="130" height="40" [left]="leftValue" [top]="topValue" ></Button>
  </AbsoluteLayout>

在 AbsoluteLayout 中放置一个 GridLayout,然后在 GridLayout 中放置应该居中的 Button:

<AbsoluteLayout  class="list-item">
    <Image src="{{item.photo}}" *ngIf="item.photo" stretch="fill">  </Image>
    <GridLayout background="transparent">
        <Button [text]="item.name" (tap)="onItemTap(item)"></Button>
    </GridLayout>
</AbsoluteLayout>

试试这个 nativescript 也接受百分比值

<AbsoluteLayout>
  <Image src="your-image-here.jpg" width="100%" height="220"></Image>
  <GridLayout top="50%" left="50%" width="100%">
    <Label text="Lorem Ipsum" textWrap="true">
 </GridLayout>
</AbsoluteLayout>