1

I try to create a semi-circe with custom paint. the problem is that it is always drawn from the center. this creates a space at the bottom area that i don't want. how can i crop it?

enter image description here

I have checked this but this question is not answered here: Flutter how to draw semicircle (half circle)

class myPainter extends CustomPainter {

@override
void paint(Canvas canvas, Size size) {
    var centerX = size.width / 2;
    var centerY = size.height / 2;
    var center = Offset(centerX, centerY);
    var radius = min(centerX, centerY);

   canvas.drawArc(Rect.fromCircle(center: center, radius: radius -25),
      doubleToAngle(-90), doubleToAngle(180), false, redCircle);

 bool shouldRepaint(bmiPainter oldDelegate) {
    //return true;
    return oldDelegate._angle != _angle;
  }

@override
  double doubleToAngle(double angle) => angle * pi / 180.0;

}

I embed the custom painter like this:

Flexible(
        flex: 2,
        fit: FlexFit.tight,
        child: Container(

              child: Transform.rotate(
                angle: -pi / 2,
                child: CustomPaint(
                  size: Size(300, 150),
                  key: backgroundKey,
                  painter: myPainter(),
                  child: Container(),
                ),
              ),
            ),
),

It has nothing to do with flexible. If I take a container and make it smaller, the semicircle also becomes smaller. I played with Size but I it does not change anything. For what exactly is Size

desmeit
  • 550
  • 1
  • 7
  • 24

1 Answers1

3

Rect.fromCircle has center argument, and you can pass size's bottomCenter value.

Here is a working example:

Custom Painter

class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final redCircle = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.stroke;
    final arcRect = Rect.fromCircle(
        center: size.bottomCenter(Offset.zero), radius: size.shortestSide);
    canvas.drawArc(arcRect, 0, -pi, false, redCircle);
  }

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

(using with bounds)

Padding(
  padding: EdgeInsets.all(16),
  child: CustomPaint(
    painter: MyPainter(),
    child: SizedBox(width: 128, height: 64),
  ),
),

(using without bounds)

Flexible(
  child: Padding(
    padding: EdgeInsets.all(16),
    child: CustomPaint(
      painter: MyPainter(),
      child: AspectRatio(
        aspectRatio: 2,
        child: SizedBox(),
      ),
    ),
  ),
),
untp
  • 151
  • 1
  • 5