flutterdartflutter-canvas

Canvas position is hard to determine in flutter


I was playing with flutter custom painter and it's behavior seems to be pretty hard to understand. enter image description here

As you can see in the above image although I've specified to draw from the top of the screen it starts from above and displays a semi circle. What i want is to start the circle at the top of the screen and it should remain same on all the devices. So what i want to achieve is something like this,

enter image description here

The circle should be positioned exactly on top of the screen.

What I've written so far,

class CustomCircle extends CustomPainter {

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.red.withOpacity(0.4)
      ..style = PaintingStyle.fill;
    canvas.drawPath(
      Path.combine(
        PathOperation.difference,
        Path()
          ..addRRect(RRect.fromLTRBR(
              0, 0, size.width, size.height, const Radius.circular(0))),
        Path()
          ..addOval(Rect.fromCircle(
              center: Offset(size.width * 0.5, 0), radius: size.width * 0.25))
          ..close(),
      ),
      paint,
    );
  }

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

= This is how I used it

  @override
      Widget build(BuildContext context) {
        return Scaffold(
            body: CustomPaint(
            child: Container(),
            painter: CustomCircle(),
        )
   

Any suggestions to achieve the above UI will be greatly appreciated.


Solution

  • As @pskink mentioned, the center of the circle is not in the right place. You can do.

    Path()
      ..addOval(
        Rect.fromCircle(
          center: Offset(size.width * 0.5, size.width * .25),
          radius: size.width * 0.25,
        ),
      )