CustomPaint
的代码:
return new Scaffold(
body:
new GestureDetector(
onTap: () {
debugPrint("hello");
},
child:
new Container(
alignment: FractionalOffset.center,
child: new CustomPaint(
size: new Size(400.0, 400.0),
painter: new BarChartPainter(currentHeight),
))),
);
//x axis code
canvas.drawLine(new Offset(0.0, 0.0), new Offset(500.0, 0.0), paintAx);```
x轴代码将从(0,0)到(500,0)绘制线,该线位于Paint
框的顶部。原点位于框的左上角。如何更改原点以使(0,0)位于绘图框的左下角?
答案 0 :(得分:0)
我不确定你怎么能操纵Canvas
区域的起源。但是,您可以在Offset
坐标上应用translation
,这样您就可以将行放在最终的位置。
我做了这个简单的例子,它可能有所帮助:
import "package:flutter/material.dart";
void main() {
runApp(new MaterialApp(home: new MyApp(),
));
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
CustomPaint _myCustomPainter = new CustomPaint(
size: new Size(400.0, 400.0),
painter: new Line(),
);
@override
Widget build(BuildContext context) {
final key = new GlobalKey<ScaffoldState>();
return new Scaffold(
key: key,
body:
new GestureDetector(
onTap: () {
debugPrint("hello");
},
child:
new Container(
alignment: FractionalOffset.center,
child: _myCustomPainter
),
),);
}
}
class Line extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
// canvas.translate(0.0, 100.0);
canvas.drawLine(new Offset(100.0, -50.0).translate(0.0, 100.0),
new Offset(0.0, 100.0).translate(0.0, 100.0),
new Paint()
);
}
@override
bool shouldRepaint(Line oldDelegate) {
// Since this Line painter has no fields, it always paints
// the same thing, and therefore we return false here. If
// we had fields (set from the constructor) then we would
// return true if any of them differed from the same
// fields on the oldDelegate.
return false;
}
}
答案 1 :(得分:0)
只需使用在画布上翻译的方法:canvas.translate(0, size.height)
。但是请注意,在这种情况下,您将需要在y轴上使用负值。
如果希望画布坐标的行为类似于经典图形,请使用scale方法:
@override
void paint(Canvas canvas, Size size) {
canvas.translate(0, size.height);
canvas.scale(1, -1);
final paint = Paint();
paint.color = Colors.black;
canvas.drawLine(Offset.zero, Offset(500, 500), paint);
}