修改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個點:工具
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.ui
咱們使用path表述貝塞爾曲線。moveTo方法移動筆到開始點的位置。最後使用drawPath方法繪製出來。spa
能夠是使用三方庫繪製虛線:https://pub.dartlang.org/packages/path_drawingcode
要使用它如今 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,第二個參數定義每一段虛線的長度和兩個虛線間的間隔長度。結果以下: