【问题标题】:Center label around anchor point in RelativeLayout with Xamarin使用 Xamarin 在 RelativeLayout 中的锚点周围居中标签
【发布时间】:2021-06-03 03:26:06
【问题描述】:

我有一个 RelativeLayout,其中有多个多边形/标签。现在我想将标签放在多边形内,在它的中心。但是,我不知道标签的宽度和高度,因此将它们放在中心会产生如下结果:

但是,这是错误的,因为无论文本是什么,我都希望标签位于多边形的正中间(宽度和高度已知)。

我已经研究了尝试使其居中的方法,例如使用HorizontalTextAlignmentVerticalTextAlignment,但到目前为止没有成功。这样做的正确方法是什么? HorizontalOptions 也不起作用,因为它与父母或其他东西无关。

我目前正在使用的代码:

var MainGrid = new RelativeLayout();
var path = new PointCollection();
// add points to path

var coords = new Point(100, 100);
var TILE_WIDTH = 70;
var TILE_HEIGHT = 80;

// Here the real code begins
polygon = new Polygon
{
    Points = path,
    <other arguments>
};
var text = new Label
{
    Text = "5",
    HorizontalTextAlignment = TextAlignment.Center,
    VerticalTextAlignment = TextAlignment.Center,
    TextColor = Color.Black,
};

MainGrid.Children.Add(
    polygon, 
    Constraint.Constant(coords.X),
    Constraint.Constant(coords.Y)
);
MainGrid.Children.Add(
    text,
    Constraint.Constant(coords.X + TILE_WIDTH / 2),
    Constraint.Constant(coords.Y + TILE_HEIGHT / 2)
);

【问题讨论】:

  • 而不仅仅是描述代码,请发布相关部分。又怎么不知道标签的宽高呢?
  • 完成,添加了一些我正在使用的代码
  • 只需在创建标签时设置宽度和高度值并以此为基础进行计算。并临时为标签设置一个 BackgroundColor,以便您可以看到它在单元格内的放置位置

标签: xamarin.forms


【解决方案1】:

在标签上设置任意宽度和高度,只要它足够大以适合您的文本并且小于多边形。还设置背景颜色以帮助可视化标签的位置(一旦对齐正确,请删除它)

var text = new Label
{
    Text = "5",
    HorizontalTextAlignment = TextAlignment.Center,
    VerticalTextAlignment = TextAlignment.Center,
    TextColor = Color.Black,
    BackgroundColor = Color.White,
    HeightRequest = 50,
    WidthRequest = 50
};

然后在放置标签时考虑标签的宽度和高度

MainGrid.Children.Add(
    text,
    Constraint.Constant(coords.X + (TILE_WIDTH / 2) - 25),
    Constraint.Constant(coords.Y + (TILE_HEIGHT / 2) - 25)
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-09
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 2012-12-27
    相关资源
    最近更新 更多