如何在对象图像Xamarin表单上方设置标签对象

问题描述 投票:0回答:2

我尝试了几种解决方案,但仍然在下面,我所做的测试是:first solution

<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>

我希望标签在图像上方,我必须做出悬停效果。

你可以找到一个动态覆盖图像的解决方案仍然是底部的标签对象吗?

c# image xamarin xamarin.forms label
2个回答
2
投票

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

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

这将使背面的图像和顶部的文本在顶部水平居中


0
投票

Answer

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

此Stack Overflow帖子提供了有关如何在Xamarin.Forms中集UI元素的更多信息:

Xamarin.Forms: How to center views using Relative Layout? `Width` and `Height` return -1

Sample Code

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 };
        }
    }
}

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.