1

I've created a custom drawn widget using CustomPaint that has a path as an outline. But wrapping the widget in a GestureDetector makes the click area a rectangle around the whole canvas, Is there a way to clip the GestureDetector so that that click only works within the path?

Johnnygizmo
  • 256
  • 1
  • 9
  • you dont have to do *anything* if you use a custom `Shape3Border` class, like: `class SB extends ShapeBorder { ...` - sample code [here](https://stackoverflow.com/a/56726277/2252830) – pskink Jul 01 '19 at 03:39
  • The package `touchable` https://github.com/nateshmbhat/touchable , is the perfect choice for this. You can give all kinds of gesture callbacks to individual shapes you draw on the canvas – Natesh bhat Apr 21 '20 at 01:19

1 Answers1

3

You can implement the hitTest method from the CustomPainter, add your Path there and use the condition path.contains(position) to ensure the touch only covers the Path part.

class MyCustomPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    // TODO: implement paint
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return null;
  }

  @override
  bool hitTest(Offset position) {
    Path path = Path();
    //add your lines/curves here
    path.close();
    return path.contains(position);
  }
}

More info about bool hitTest(Offset position):

Called whenever a hit test is being performed on an object that is using this custom paint delegate.

The given point is relative to the same coordinate space as the last [paint] call.

The default behavior is to consider all points to be hits for background painters, and no points to be hits for foreground painters.

Return true if the given position corresponds to a point on the drawn image that should be considered a "hit", false if it corresponds to a point that should be considered outside the painted image, and null to use the default behavior.

I answered a similar question here: Flutter: What is the correct way to detect touch enter, move and exit on CustomPainter objects

diegoveloper
  • 93,875
  • 20
  • 236
  • 194