【发布时间】:2022-01-18 10:39:33
【问题描述】:
在 Flutter 中使用 Canvas 和 Path 绘制自定义形状和线条。 我想在 Flutter 中使用 Canvas 和 Path 绘制自定义形状和线条。我想用 GestureDetector 做到这一点。我想从 0,0 开始,然后回到 0,0。简而言之,我想手工绘制和创建我想要的形状。我该怎么做。
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
State<MyHomePage> createState() => _MyHomePageState();
}
double x = 100;
double y = 200;
double X_Position = 0.00;
// ignore: non_constant_identifier_names
double Y_Position = 0.00;
class _MyHomePageState extends State<MyHomePage> {
final key = GlobalKey();
// ignore: non_constant_identifier_names
@override
void initState() {
// TODO: implement initState
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(X_Position.toString()),
),
body: Stack(
children: [
GestureDetector(
onPanStart: (details) {
Offset position = details.localPosition;
setState(() {
X_Position = position.dx;
Y_Position = position.dy;
});
},
onPanUpdate: (details) {
Offset position = details.localPosition;
setState(() {
X_Position = position.dx;
Y_Position = position.dy;
print(X_Position);
print(Y_Position);
});
},
child: Container(
key: key,
width: 500,
height: 500,
decoration: BoxDecoration(
color: Colors.yellow,
border: Border.all(
color: Colors.black,
width: 2,
),
),
child: LayoutBuilder(
// Inner yellow container
builder: (_, constraints) => Container(
width: constraints.widthConstraints().maxWidth,
height: constraints.heightConstraints().maxHeight,
color: Colors.yellow,
child: CustomPaint(painter: FaceOutlinePainter()),
),
),
),
),
],
),
);
}
}
class FaceOutlinePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
// TODO: draw something with canvas
final paint = Paint();
paint.style = PaintingStyle.stroke;
paint.strokeWidth = 4.0;
paint.color = Colors.indigo;
canvas.drawLine(
Offset(X_Position, size.height / 2),
Offset(Y_Position, size.height / 2),
paint,
);
}
@override
bool shouldRepaint(FaceOutlinePainter oldDelegate) => false;
}
例如,我想在屏幕上画一个正方形。我会用手随机画正方形。在屏幕上画线时,我会将传入的每个点的 x 和 y 坐标保存在一个数组中。我想在offset的帮助下画画。它们的值应该来自手势检测器。我想只使用 canvas.drawLine 来制作我的形状。
【问题讨论】: