Created
April 29, 2020 12:35
-
-
Save stegrams/4d594c3f7afaee995d533487b422cb30 to your computer and use it in GitHub Desktop.
A mathematical graph sample code with CustomPainter and Canvas.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
home: Scaffold( | |
body: Center( | |
child: MyWidget(), | |
), | |
), | |
); | |
} | |
} | |
class MyWidget extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
// Based on https://youtu.be/vvI_NUXK00s | |
return FittedBox( | |
fit: BoxFit.fill, | |
child: SizedBox( | |
width: 250, | |
height: 150, | |
child: Container( | |
color: Colors.grey[200], | |
child: CustomPaint( | |
painter: PathPainter(), | |
), | |
), | |
), | |
); | |
} | |
} | |
class PathPainter extends CustomPainter { | |
@override | |
void paint(Canvas canvas, Size size) { | |
Offset pointA = Offset(size.width * 1 / 16, size.height * 3 / 4); | |
Offset pointB = Offset(size.width * 11 / 16, size.height * 1 / 4); | |
double handleW = size.width * 2 / 64; | |
Rect handleA = | |
Rect.fromCenter(center: pointA, width: handleW, height: handleW); | |
Rect handleB = | |
Rect.fromCenter(center: pointB, width: handleW, height: handleW); | |
Paint paint = Paint() | |
..style = PaintingStyle.stroke | |
..strokeWidth = 2.0; | |
Path axes = Path() | |
..moveTo(size.width / 2, 0) | |
..lineTo(size.width / 2, size.height) | |
..moveTo(0, size.height * 3 / 5) | |
..lineTo(size.width, size.height * 3 / 5) | |
..close(); | |
Path line = Path() | |
..moveTo(pointA.dx, pointA.dy) | |
..lineTo(pointB.dx, pointB.dy) | |
..close(); | |
Path handles = Path() | |
..addRect(handleA) | |
..addRect(handleB) | |
..close(); | |
canvas.drawPath(axes, paint..color = Colors.black); | |
canvas.drawPath(line, paint..color = Colors.red); | |
paint.strokeWidth = 1.0; | |
canvas.drawPath(handles, paint..color = Colors.black); | |
} | |
@override | |
bool shouldRepaint(CustomPainter oldDelegate) => false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment