颤振自定义画家

Flutter Custom Painter

你好,我创建了一个扩展 CustomPainter 的小部件。问题是当调用 paint 方法时,Size 参数宽度和高度字段始终为 0,0 我不确定如何解决此问题。任何想法将不胜感激。这是小部件。谢谢!!

class Box extends CustomPainter {
  double _top = 0.0;
  double _left = 0.0;
  double _width = 0.0;
  double _height = 0.0;
  String _text;

  Box(this._top, this._left, this._width, this._height, this._text);

  @override
  void paint(Canvas canvas, Size size) {
   canvas.drawRect(
      new Rect.fromLTWH(_left, _top, _width, _height),
      new Paint()
        ..style = PaintingStyle.stroke
        ..strokeWidth = 2.0
        ..color = Colors.blue // new Color(0xFF0099FF),
  );
}

 @override
 bool shouldRepaint(Box oldDelegate) {
  return false;
 }
}

并这样使用它:

new Positioned(
      left: 0.0,
      top: 0.0,
      child: new Container(
          child:new CustomPaint(
          painter: new Box(block.boundingBox.top.toDouble(), block.boundingBox.left.toDouble(),
              block.boundingBox.width.toDouble(), block.boundingBox.height.toDouble(),
              block.text)
      ))
  )

再次感谢您可能有的想法!

多一点代码会有所帮助,但我想我可以对您在这里所做的事情给出充分的解释。

我假设您的 Positioned 在堆栈中,并且由于堆栈中的另一个元素(或者由于放置在赋予其大小的小部件中),堆栈具有大小。例如,如果堆栈位于 SizedBox、Container(指定大小)或类似的容器中,它将有一个大小。而如果它位于中心,它会根据其子项调整自身大小。

在堆栈大小由其子项确定的情况下,它根据最大的 非定位 子项(即未包装的子项)确定它的大小在 Positioned 中或包裹在 Positioned 中但定位不定义任何左、右、上、右、宽度或高度。

所以回到你的问题 - 如果我们假设堆栈有一个大小,那么你的小部件将被放置在左上角。但是,正如您 Positioned 下所写的 none 小部件实际上指定了它们自己的大小 - 您还没有设置 Container 或 CustomPaint 的大小。

所以您需要做的实际上是指定您希望 CustomPaint 有多大。如果您知道特定的 width/height,则可以在 Container 或 CustomPaint 的大小中指定它。如果您不希望它拉伸到堆栈的大小,您可以简单地删除 Positioned 小部件,或者同时定义 left/right and/or top/bottom。或者您可以组合指定的高度或宽度 + 与您想要的尺寸的偏移量。最后一件事是 CustomPaint 可能仍然决定将自身的大小调整为零,即使外面的小部件大小合适。如果是这种情况,您需要传入一个尺寸(我相当确定如果传入 Size.infinite 它将扩展以填充其父级)。

最后一件事是,我不确定您在使用 CustomPainter 做什么,但它似乎可能是错误的。如果您所做的只是尝试绘制一个正方形,请使用传递给画家的尺寸而不是参数(我猜您正在尝试这样做以解决您看到的尺寸为零的问题).

例如,如果您想简单地绘制一个填充整个绘画区域的矩形,请使用:

canvas.drawRect(Offset.zero & size, Paint().....);

但是,如果您传递内容,则需要确保您没有在自定义画家的范围之外绘图。来自 CustomPaint 文档:

The painters are expected to paint within a rectangle starting at the origin and encompassing a region of the given size. (If the painters paint outside those bounds, there might be insufficient memory allocated to rasterize the painting commands and the resulting behavior is undefined.)

CustomPaint 小部件的默认大小为 Size.zero。要给出您喜欢的尺寸,请使用:

CustomPaint(
size: Size(100,100),
painter: MyPainter(),
),

要根据您的设备提供 canvas 宽度和高度,您可以使用

double deviceWidth = MediaQuery.of(context).size.width;
double deviceHeight = MediaQuery.of(context).size.height;

在您的构建方法中初始化 deviceWidth 和 deviceHeight,并将其传递给 CustomPaint 小部件的大小 属性。

CustomPaint(
size: Size(deviceWidth,deviceHeight),
painter: MyPainter(),
),