简体   繁体   English

如何将文本绘制为自定义画家形状的子项 Flutter

[英]How to draw Text as a child of Custom Painter shape Flutter

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我正在尝试将 Text 小部件置于使用 Custom Painter 制作的自定义形状中 我尝试放置Stack小部件但它失败了 我用谷歌搜索并找到了TextPainter并尝试使用它 我不知道它是否是正确的解决方案但我无法实现什么我想了

I want to achieve the button with green arrow i currently have the button with yellow arrow我想实现带绿色箭头的按钮我目前有带黄色箭头的按钮

在此处输入图像描述

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;
}

}

在此处输入图像描述

After inspecting your canvas, you can see that it is not drawn correctly, so you do not see the text on the shape.检查您的 canvas 后,您会发现它没有正确绘制,因此看不到形状上的文字。

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要么重新制作形状,要么尝试调整到此偏移量,这将使您一开始就可以看到形状上的文本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM