1

I am using CustomPaint to draw some rectangle. But there are visible lines inside my canvas.

Current output

enter image description here

Expected output

enter image description here

Code to reproduce the issue

void main() => runApp(const MaterialApp(home: CustomPaintIssue()));

class CustomPaintIssue extends StatelessWidget {
  const CustomPaintIssue({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SizedBox(
          width: 500,
          height: 500,
          child: CustomPaint(
            painter: MyPainter(),
          ),
        ),
      ),
    );
  }
}

class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    const div = 34;
    Size blocSize = Size(size.width / div, size.height / div);

    for (int i = 0; i < div; i++) {
      for (int j = 0; j < div; j++) {
        canvas.drawRect(
          Rect.fromLTWH(
            i * blocSize.width,
            j * blocSize.height,
            blocSize.width,
            blocSize.height,
          ),
          Paint()
            ..color = Colors.red
            ..style = PaintingStyle.fill,
        );
      }
    }
  }

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

Instead of extending rect size, there should be better explanation for this type of behavior, that is what I am looking for and how to overcome this situation.

Flutter 3.0.1 & Dart 2.17.1

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56

1 Answers1

0

The issue is if you divide 500 by 34 you get 14.7058823529 and multipluing this with 34 will give 499.99999 which is not 500. Hence each block has a very small space. To overcome this you can either divide it witha number like 25 or 20 which will not end up in a decimal value or give a background color for the container that holds this custom paint

preview1

preview2

preview3

Kaushik Chandru
  • 15,510
  • 2
  • 12
  • 30