我尝试使用Flutter中的Canvas
将CustomPainter
中的项目居中,范围从TextPaints到普通圆圈。
通常,在将自定义颜料居中时,我会将Offset
设置为Offset(size.width/2, size.height/2)
。但这不起作用,我的项目被拉到 Canvas 的右下角。
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: Container(
child: LayoutBuilder(builder: (context, constraints) {
return Container(
width: constraints.widthConstraints().maxWidth,
height: constraints.widthConstraints().maxHeight,
child: CustomPaint(
painter: FollowPainter(),
),
);
}),
));
}
}
class FollowPainter extends CustomPainter {
static final fill = Paint()..color = Colors.black;
@override
void paint(Canvas canvas, Size size) {
TextSpan span = new TextSpan(
style: new TextStyle(
color: Colors.black, fontSize: 50, fontWeight: FontWeight.w700),
text: 'Hello World');
TextPainter tp = new TextPainter(
text: span,
textAlign: TextAlign.left,
textDirection: TextDirection.ltr);
tp.layout();
tp.paint(canvas, new Offset(size.width / 2, size.height / 2));
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
// TODO: implement shouldRepaint
throw UnimplementedError();
}
我怀疑问题可能是因为我是从该偏移开始绘制,而不是从中心开始绘制。那么如何在CustomPainter中将绘制的小部件居中?
最佳答案
I suspect that the problem could be the fact that I'm starting the drawing from that Offset, instead of drawing from the center.
您是对的,只需从宽度减去文本宽度的一半,再从高度减去文本高度的一半。
tp.paint(canvas, new Offset(size.width / 2 - tp.width / 2, size.height / 2 - tp.height / 2));
关于flutter - 使用CustomPaint在 Canvas 上居中放置项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63059326/