Home > database >  How to draw an Arc in the middle of CustomPainter shape
How to draw an Arc in the middle of CustomPainter shape

Time:10-07

I am trying to draw the following shape using CustomPainter, I am looking for a way to make this shape as one shape (union), so for example using Stack with Container and half circle shape is not desired.

enter image description here

I have managed to paint the base rectangular shape as the following image shows, is it possible to build on top of this code to draw a half a circle in the middle ?

enter image description here

Container(
              height: 85,
              color: Colors.blueGrey,
              child: Stack(
                children: [
                  CustomPaint(
                    size: Size(size.width, 85),
                    painter: MyCustomPainter(),
                  )
                ],
              ),
            ),
class MyCustomPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.fill;

    var path = Path()..moveTo(0, 20);

    path.quadraticBezierTo(0, 0, 0, size.height * 0.5);
    path.quadraticBezierTo(0, 0, size.width * 0.2, 0);

    path.quadraticBezierTo(size.width, 0, size.width * 0.8, 0);
    path.quadraticBezierTo(size.width, 0, size.width, size.height * 0.5);
    path.lineTo(size.width, size.height);
    path.lineTo(0, size.height);

    canvas.drawPath(path, paint);
  }

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

CodePudding user response:

While the question about using union operation, I am focusing on

 canvas.drawPath(
        Path.combine(PathOperation.union, path1, circlePath), paint);

The current paint takes full height and doesnt maintain the ration based on your desire result. I am using Rect on Path to demonstrating the union operation. Change the size/value according to your needs.

class MyCustomPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.fill;

    final double base = size.height * .4;

    const corner = Radius.circular(16);

    final path1 = Path()
      ..addRRect(
        RRect.fromLTRBAndCorners(0, base, size.width, size.height,
            topLeft: corner, topRight: corner),
      );

    final center = Offset(size.width / 2, size.height / 2);

    final radius = size.height / 2;

    final circlePath = Path()
      ..addOval(Rect.fromCircle(center: center, radius: radius));

    canvas.drawPath(
        Path.combine(PathOperation.union, path1, circlePath), paint);
  }

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

enter image description here

More about CustomPaint

  • Related