天天看点

第二十一章:变换(二)翻译变换

翻译变换

应用程序使用其中一个布局类 - StackLayout,Grid,AbsoluteLayout或RelativeLayout-在屏幕上定位可视元素。 让我们将布局系统建立的位置称为“布局位置”。

TranslationX和TranslationY属性的非零值会更改可视元素相对于该布局位置的位置。 TranslationX的正值将元素向右移动,而TranslationY的正值将元素向下移动。

TranslationDemo程序允许您试验这两个属性。 一切都在XAML文件中:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TranslationDemo.TranslationDemoPage">
    <StackLayout Padding="20, 10">
        <Frame x:Name="frame"
               HorizontalOptions="Center"
               VerticalOptions="CenterAndExpand"
               OutlineColor="Accent">
 
            <Label Text="TEXT"
                   FontSize="Large" />
        </Frame>
        <Slider x:Name="xSlider"
                Minimum="-200"
                Maximum="200"
                Value="{Binding Source={x:Reference frame},
                Path=TranslationX}" />
        <Label Text="{Binding Source={x:Reference xSlider},
               Path=Value,
               StringFormat='TranslationX = {0:F0}'}"
               HorizontalTextAlignment="Center" />
        <Slider x:Name="ySlider"
                Minimum="-200"
                Maximum="200"
                Value="{Binding Source={x:Reference frame},
                Path=TranslationY }" />
        <Label Text="{Binding Source={x:Reference ySlider},
               Path=Value,
               StringFormat='TranslationY = {0:F0}'}"
               HorizontalTextAlignment="Center" />
    </StackLayout>
</ContentPage>           

框架包含一个Label,并在StackLayout的上半部分居中。 两个Slider元素绑定到Frame的TranslationX和TranslationY属性,并且它们被初始化为-200到200的范围。当您第一次运行程序时,两个滑块被设置为TranslationX和TranslationY的默认值, 为零:

第二十一章:变换(二)翻译变换

您可以操纵滑块以在屏幕上移动框架。 TranslationX和TranslationY的值指定元素相对于其原始布局位置的偏移量:

第二十一章:变换(二)翻译变换

如果值足够大,则可以将元素转换为与其他视觉效果重叠,或者完全移出屏幕。

诸如Frame之类的元素的转换也会影响该元素的所有子元素,在这种情况下,它只是Label。您可以在任何VisualElement上设置TranslationX和TranslationY属性,包括StackLayout,Grid,甚至Page及其派生词。变换应用于元素和该元素的所有子元素。

没有一点调查可能不那么明显的是,TranslationX和TranslationY仅影响元素的呈现方式。这些属性不会影响布局系统中元素的感知方式。

例如,VisualElement定义名为X和Y的get-only属性,指示元素相对于其父元素的位置。当元素由其父元素定位时,将设置X和Y属性,在此示例中,Frame的X和Y属性指示Frame的左上角相对于StackLayout左上角的位置。设置TranslationX和TranslationY时,X和Y属性不会更改。此外,只有Bounds属性 - 它将X和Y以及Width和Height组合在一个Rectangle中 - 也不会改变。修改TranslationX和TranslationY时,布局系统不会涉及。

如果您使用TranslationX和TranslationY将Button从其原始位置移动会发生什么? Button是否响应其原始布局位置或新渲染位置的水龙头?你会很高兴知道它是后者。 TranslationX和TranslationY会影响元素的呈现方式以及它如何响应水龙头。您很快就会在名为ButtonJump的示例程序中看到这一点。

如果需要在页面周围进行大量的元素移动,您可能想知道是否使用AbsoluteLayout并明确指定坐标或使用TranslationX和TranslationY来指定偏移。 在性能方面,实际上差别不大。 TranslationX和TranslationY的优点是你可以从StackLayout或Grid建立的位置开始,然后相对于该位置移动元素。

继续阅读