Search code examples
flutterdartflutter-layoutflutter-custompainter

Cutting transparent rectangle using canvas from filled rectangle Dart


I pin the picture of how it should looks like. I was trying ti use Cnavas, because as I inderstood such things can't be done by simple widget. So I have a question, how can I extract rectangle from this filled rectangle? I saw solution like this:

class TransparantRectanglePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint();
    paint.color = Colors.blue;
    canvas.drawPath(
      Path.combine(
        PathOperation.difference,
        Path()
          ..addRRect(RRect.fromLTRBR(100, 100, 300, 300, Radius.elliptical(x: 10, y: 15))),
        Path()
          ..addRect(Rect.fromLTRB(100, 100, 100, 100)
          ..close(),
      ),
      paint,
    );
  }

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

enter image description here


Solution

  • As for the fromLTRBR,

    Construct a rounded rectangle from its left, top, right, and bottom edges, and the same radius in each corner.

    And fromLTRB

    Construct a rectangle from its left, top, right, and bottom edges.

    It is better to use size rather than hard coded value.

    If you want round corner, use addRRect, quadraticBezierTo or relativeQuadraticBezierTo etc.

    class TransparentRectanglePainter extends CustomPainter {
      @override
      void paint(Canvas canvas, Size size) {
        final paint = Paint();
        paint.color = Colors.red;
    
        final Path path1 = Path()
          ..addRRect(
            RRect.fromLTRBR(
                0, 0, size.width, size.height, const Radius.elliptical(10, 15)),
          );
    
        final Path path2 = Path()
          ..addRect(
            Rect.fromLTRB(0, size.height / 2, size.width / 2, size.height),
          );
    
        canvas.drawPath(
          Path.combine(PathOperation.difference, path1, path2),
          paint,
        );
      }
    
      @override
      bool shouldRepaint(TransparentRectanglePainter oldDelegate) =>
          this != oldDelegate;
    }
    

    enter image description here

    Visit flutter.dev to learn more about CustomPaint widget.