Flutter如何绘制矩形

在Flutter中,我想绘制一个自定义大小的矩形,但不太清楚具体该用什么组件或方法实现。是用CustomPaint配合Canvas手动绘制,还是直接用Container设置decoration?两种方式的具体代码怎么写?哪种性能更好?如果矩形需要添加圆角或边框又该如何处理?求详细示例代码和最佳实践建议。

2 回复

Flutter中绘制矩形可使用ContainerCustomPaint

  1. Container:设置decoration属性,如BoxDecoration并指定colorborder
  2. CustomPaint:使用CustomPaint组件,在paint方法中调用canvas.drawRect()绘制。
    示例代码简单,适合快速实现。

更多关于Flutter如何绘制矩形的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中,绘制矩形可以通过以下几种方式实现:

1. 使用Container组件

最简单的方式是使用Container组件,通过设置decoration属性来绘制矩形:

Container(
  width: 200,
  height: 100,
  decoration: BoxDecoration(
    color: Colors.blue, // 填充颜色
    border: Border.all(
      color: Colors.black, // 边框颜色
      width: 2.0, // 边框宽度
    ),
    borderRadius: BorderRadius.circular(8.0), // 圆角矩形
  ),
)

2. 使用CustomPaint自定义绘制

如果需要更复杂的绘制,可以使用CustomPaint组件:

CustomPaint(
  size: Size(200, 100),
  painter: RectanglePainter(),
)

class RectanglePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.fill; // 填充样式
    
    final rect = Rect.fromLTWH(0, 0, size.width, size.height);
    canvas.drawRect(rect, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

3. 绘制带边框的矩形

class RectanglePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    // 填充矩形
    final fillPaint = Paint()
      ..color = Colors.blue
      ..style = PaintingStyle.fill;
    
    // 边框矩形
    final borderPaint = Paint()
      ..color = Colors.black
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;
    
    final rect = Rect.fromLTWH(0, 0, size.width, size.height);
    canvas.drawRect(rect, fillPaint);
    canvas.drawRect(rect, borderPaint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

4. 使用PhysicalModel组件

PhysicalModel(
  color: Colors.green,
  elevation: 4.0,
  borderRadius: BorderRadius.circular(8.0),
  child: Container(
    width: 200,
    height: 100,
  ),
)

推荐使用Container方式,因为它最简单且性能最佳。只有在需要复杂自定义绘制时才使用CustomPaint。

回到顶部