Home > Software design >  How to draw Text as a child of Custom Painter shape Flutter
How to draw Text as a child of Custom Painter shape Flutter

Time:03-18

I am trying to center a Text widget in a custom shape made using Custom Painter i tried laying a Stack widget but it failed i googled and found about TextPainter and tried to use it I dont know if its the right solution but i could not acheive what i wanted

I want to achieve the button with green arrow i currently have the button with yellow arrow

enter image description here

Any Idea?

class CustomShape1 extends CustomPainter{

@override
void paint(Canvas canvas, Size size) {

TextPainter textPainter = TextPainter(
    text: TextSpan(
      text: 'Foo\nBar',
      style: TextStyle(
        color: Colors.white,
        fontSize: 30,
      ),
    ),
    textDirection: TextDirection.ltr,
    textAlign: TextAlign.center
);


Paint fillPaint = Paint();
fillPaint.color = const Color(0xFF830B2C);
fillPaint.style = PaintingStyle.fill;

Path path = Path();
path.moveTo(size.width*0.5000125,size.height*0.2996000);

path.cubicTo(size.width*0.6875031,size.height*0.2990750,
size.width*0.6871875,size.height*0.2979000,size.width*0.7500000,size.height*0.2989000);

path.quadraticBezierTo(size.width*0.7645125,size.height*0.5243200,
size.width*0.9373000,size.height*0.6009200);

path.lineTo(size.width*0.9373000,size.height*0.6395600);
path.lineTo(size.width*0.5000500,size.height*0.6401600);

path.quadraticBezierTo(size.width*0.5000406,size.height*0.5550200,
size.width*0.5000125,size.height*0.2996000);

path.close();

canvas.drawPath(path, fillPaint);

textPainter.layout(
  minWidth: 0,
  maxWidth: size.width,
);

final offset = Offset(50 - (textPainter.width / 2), 100 - (textPainter.height / 2));
textPainter.paint(canvas,offset);

}

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

}

CodePudding user response:

enter image description here

After inspecting your canvas, you can see that it is not drawn correctly, so you do not see the text on the shape.

final offset = Offset(size.width / 2   50, size.height / 2); //text offset

either remake the shape, or try to adjust to this offset, this will give you the visibility of the text on the shape for a start

  • Related