Created
June 8, 2020 16:38
-
-
Save Barttje/e1113a67132768c1c0270b52c11de391 to your computer and use it in GitHub Desktop.
Drawing three overlapping circles with click detection
This file contains 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'; | |
import 'package:flutter/rendering.dart'; | |
void main() => runApp(HexagonGridDemo()); | |
class HexagonGridDemo extends StatelessWidget { | |
final GlobalKey blueCircle = new GlobalKey(); | |
final GlobalKey redCircle = new GlobalKey(); | |
final GlobalKey yellowCircle = new GlobalKey(); | |
final result = BoxHitTestResult(); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
home: Scaffold( | |
appBar: AppBar( | |
title: Text('Hexagon Grid Demo'), | |
), | |
body: Listener( | |
onPointerDown: (PointerEvent details) { | |
handleClick(details); | |
}, | |
child: Stack( | |
children: <Widget>[ | |
CustomPaint( | |
key: blueCircle, | |
painter: CirclePainter(Offset(90, 120), 70, Colors.blue), | |
child: Container(), | |
), | |
CustomPaint( | |
key: redCircle, | |
painter: CirclePainter(Offset(60, 60), 50, Colors.red), | |
child: Container(), | |
), | |
CustomPaint( | |
key: yellowCircle, | |
painter: CirclePainter(Offset(140, 70), 40, Colors.yellow), | |
child: Container(), | |
) | |
], | |
), | |
), | |
), | |
); | |
} | |
handleClick(PointerEvent details) { | |
if (isClicked(details, redCircle)) { | |
print("clicked the red circle"); | |
} | |
if (isClicked(details, blueCircle)) { | |
print("clicked the blue circle"); | |
} | |
if (isClicked(details, yellowCircle)) { | |
print("clicked the yellow circle"); | |
} | |
} | |
bool isClicked(final PointerEvent details, final GlobalKey key) { | |
final RenderBox circleBox = key.currentContext.findRenderObject(); | |
Offset localClick = circleBox.globalToLocal(details.position); | |
if (circleBox.hitTest(result, position: localClick)) { | |
return true; | |
} | |
return false; | |
} | |
} | |
class CirclePainter extends CustomPainter { | |
final double radius; | |
final Offset center; | |
final Color color; | |
CirclePainter(this.center, this.radius, this.color); | |
@override | |
void paint(Canvas canvas, Size size) { | |
Paint paint = Paint()..color = color; | |
canvas.drawCircle(center, radius, paint); | |
} | |
@override | |
bool shouldRepaint(CustomPainter oldDelegate) => false; | |
@override | |
bool hitTest(Offset position) { | |
final Path path = new Path(); | |
path.addRect(Rect.fromCircle(center: center, radius: radius)); | |
return path.contains(position); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment