繁体   English   中英

如何在Xamarin形式的对象图像上方设置标签对象

[英]how to set a label object above an object image Xamarin forms

我尝试了几种解决方案,但仍低于,我也做了测试: 第一个解决方案

<RelativeLayout x:Name="locationLayout" Grid.Row="0" Grid.Column="0" VerticalOptions="End" HorizontalOptions="End">
   <Image x:Name="locationIcon"/>
   <Label Text="Posizione" x:Name="posizioneLabel" TextColor="#fff" HorizontalTextAlignment="Center" FontSize="Medium"></Label>
</RelativeLayout>

我希望标签位于图像上方,我必须进行悬停效果。

您可以找到一种解决方案,可以动态地在图像上方将标签对象保留在底部?

您可以尝试将对象放在同一Grid

<Grid>
   <Image x:Name="locationIcon"/>
   <Label Text="Posizione" x:Name="posizioneLabel" TextColor="#fff" HorizontalTextAlignment="Center" FontSize="Medium"></Label>
</Grid>

这将在背面渲染图像,而在顶部水平居中显示文本。

回答

实现此目的的最佳方法是在C#代码背后创建视图,因为在代码背后,我们可以利用Func来动态调整UI的大小并使UI相对于其他元素对齐。

此Stack Overflow帖子具有有关如何在Xamarin.Forms中居中UI元素的更多信息:

Xamarin.Forms:如何使用相对布局将视图居中? 宽度和高度返回-1

样例代码

using System;

using Xamarin.Forms;

namespace SampleApp
{
    public class App : Application
    {
        public App()
        {
            var floatingLabel = new Label
            {
                Text = "This Label Is Centered"
            };

            var circleImage = new Image
            {
                Source = "circle"
            };

            var relativeLayout = new RelativeLayout();

            Func<RelativeLayout, double> getfloatingLabelHeight = (p) => floatingLabel.Measure(p.Width, p.Height).Request.Height;
            Func<RelativeLayout, double> getfloatingLabelWidth = (p) => floatingLabel.Measure(p.Width, p.Height).Request.Width;

            Func<RelativeLayout, double> getCircleImageHeight = (p) => circleImage.Measure(p.Width, p.Height).Request.Height;
            Func<RelativeLayout, double> getCircleImageWidth = (p) => circleImage.Measure(p.Width, p.Height).Request.Width;

            relativeLayout.Children.Add(circleImage,
                Constraint.RelativeToParent(parent => parent.Width / 2 - getCircleImageWidth(parent) / 2),
                Constraint.RelativeToParent(parent => parent.Height / 2 - getCircleImageHeight(parent) / 2)
            );
            relativeLayout.Children.Add(floatingLabel,
                Constraint.RelativeToView(circleImage, (parent, view) => view.X + getCircleImageWidth(parent) / 2 - getfloatingLabelWidth(parent) / 2),
                Constraint.RelativeToView(circleImage, (parent, view) => view.Y + getCircleImageHeight(parent) / 2 - getfloatingLabelHeight(parent) / 2)
            );

            MainPage = new ContentPage { Content = relativeLayout };
        }
    }
}

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM