Skip to content

Instantly share code, notes, and snippets.

@stegrams
Last active May 24, 2020 11:39
Show Gist options
  • Save stegrams/6d5dcfde1cede24c8899c5330a36dc89 to your computer and use it in GitHub Desktop.
Save stegrams/6d5dcfde1cede24c8899c5330a36dc89 to your computer and use it in GitHub Desktop.
Shape rendering and intersection with Path and Path.combine.
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: Container(
width: 600,
height: 600,
color: Colors.grey[200],
child: MyWidget(),
),
),
),
);
}
}
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
Path p = Path();
p..addPolygon(poly1, true)..addPolygon(poly2, true);
Rect bounds = p.getBounds();
// Fit it to any parent dimensions
// Based on https://youtu.be/vvI_NUXK00s
return FittedBox(
fit: BoxFit.fill,
child: SizedBox(
width: bounds.width + 2 * bounds.left,
height: bounds.height + 2 * bounds.top,
child: CustomPaint(
painter: PathPainter(poly1, poly2),
),
),
);
}
}
class PathPainter extends CustomPainter {
const PathPainter(this.polyA, this.polyB);
final List<Offset> polyA;
final List<Offset> polyB;
@override
void paint(Canvas canvas, Size size) {
Paint paint = Paint()..style = PaintingStyle.fill;
Path p1 = Path()
..addPolygon(polyA, true)
..close();
Path p2 = Path()
..addPolygon(polyB, true)
..close();
canvas.drawPath(p1, paint..color = Colors.yellow);
canvas.drawPath(p2, paint..color = Colors.cyan);
// Path.combine is not implemented on web
// https://github.com/flutter/flutter/issues/44572
try {
Path interP1P2 = Path.combine(PathOperation.intersect, p1, p2);
canvas.drawPath(interP1P2, paint..color = Colors.red);
} on UnimplementedError {
print('Path.combine is not implemented in this context.');
}
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => false;
}
final poly1 = <Offset>[
Offset(170, 19),
Offset(243, 17),
Offset(274, 69),
Offset(213, 150),
Offset(146, 155),
Offset(139, 80),
];
final poly2 = <Offset>[
Offset(195, 60),
Offset(345, 60),
Offset(345, 140),
Offset(195, 140),
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment