定位文本窗口小部件,使窗口小部件的中心位于父堆栈的特定位置

时间:2020-07-20 14:32:28

标签: flutter flutter-layout

我有一个Stack()小部件,里面有一个子Text()小部件。我需要“文本”小部件的中心位于[左:137,上:201]。

使用Positioned(),我只能定位对象的边缘。如何定位“文本”小部件的中心?有没有一种方法可以使用子窗口小部件的宽度/高度来抵消Positioned(),还是其他方式?

Stack(
        children: [
          ...,
          Positioned(
              left: 137,    // I want these coordinates to be the center
              top: 201,     // but they are the top left corner now
              child: Text("20%")
          )])

用Center()包裹Text()小部件似乎没有任何作用?

I have a CustomPainter that draws graphics, and I can get the pixel coordinates of any painted point. I want to overlay text, and I want to be able to center the text on a specific point. In this picture I woudl like the "20%" text to be centered on the middle cross between green/blue, but I can only set the top left corner with Positioned()

我有一个CustomPainter来绘制属于同一Stack()的图形,并且我可以获取任何绘制点的像素坐标。我想覆盖文本,并且希望能够使文本在特定点上居中。在此图片中,我希望“ 20%”文本位于绿色/蓝色(x:137,y:201)之间的中间十字的中心,但是我只能使用Positioned()设置左上角

1 个答案:

答案 0 :(得分:0)

解决了这个问题。我可以使容器的硬编码大小大于文本大小。现在,我可以将Center小部件作为容器的子级,将Text小部件置于Center小部件内。 Presto,我可以使用Container的尺寸+坐标来精确定位文本。

Positioned(
    top: y-100,
    left: x-100,
    child: Container(
          width: 200,  // Now I just offset my Positioned() parameters
          height: 200, // by half the width & height as done above
          child: Center(
              child: Text(
            "Hello!"
          ))));