修改main.dart文件:canvas
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Drawing Shapes",
home: DrawingPage(),
);
}
}
class DrawingPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Curved Line"),
),
body: CustomPaint(
painter: CurvePainter(),
child: Container(),
),
);
}
}
class CurvePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}
复制代码
接下来咱们在CurvePainter中实现绘制:app
这里使用贝塞尔曲线绘制,须要4个点,分别是:起点,终点和两个控制点,像图中那样,移动控制点就能改变曲线形状。你能够在在线工具中尝试:less
咱们使用 cubicTo
方法设置路径path:ide
void cubicTo(double x1, double y1, double x2, double y2, double x3, double y3)
复制代码
函数绘制路径从当前点到(x3,y3),控制点是(x1,y1),(x2,y2)函数
正如你看到的,cubicTo
方法接受3个点做为参数,前两个表明控制点,最后一个是结束点。开始点就是你的pen当前坐在canvas中的点。工具
canvas的坐标系是左上角是(0,0)。右下角是(size.width, size.height)。因此能够尝试调整4个点:ui
void paint(Canvas canvas, Size size) {
var paint = Paint();
paint.color = Colors.lightBlue;
paint.style = PaintingStyle.stroke;
paint.strokeWidth = 3;
var startPoint = Offset(0, size.height / 2);
var controlPoint1 = Offset(size.width / 4, size.height / 3);
var controlPoint2 = Offset(3 * size.width / 4, size.height / 3);
var endPoint = Offset(size.width, size.height / 2);
var path = Path();
path.moveTo(startPoint.dx, startPoint.dy);
path.cubicTo(controlPoint1.dx, controlPoint1.dy,
controlPoint2.dx, controlPoint2.dy,
endPoint.dx, endPoint.dy);
canvas.drawPath(path, paint);
}
复制代码
paint
对象就是至关于咱们的笔,被设置了蓝色和宽度为3.spa
咱们使用path表述贝塞尔曲线。moveTo方法移动笔到开始点的位置。最后使用drawPath方法绘制出来。code
能够是使用三方库绘制虚线:pub.dartlang.org/packages/pa…cdn
要使用它如今 pubspec.yml文件添加这个库:
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^0.1.2 path_drawing: ^0.4.0 复制代码
运行“flutter packages get”得到库,而后导入头文件就能够使用了:
import 'package:path_drawing/path_drawing.dart';
复制代码
把上面的路径用dashPath包裹一下就能够了:
canvas.drawPath(
dashPath(
path,
dashArray: CircularIntervalList<double>(<double>[15.0, 10.5]),
),
paint,
);
复制代码
dashPath
方法接受两个参数,第一个就是要绘制的path,第二个参数定义每一段虚线的长度和两个虚线间的间隔长度。结果以下: