flutter - 如何使用路径剪辑 GestureDetector(或 InkWell)输入区域?

标签 flutter

我已经使用 CustomPaint 创建了一个自定义绘制的小部件,它以路径作为轮廓。但是将小部件包裹在 GestureDetector 中会使点击区域成为围绕整个 Canvas 的矩形,有没有办法剪辑 GestureDetector 以便点击仅在路径内有效?

最佳答案

您可以从 CustomPainter 实现 hitTest 方法,在其中添加您的 Path 并使用条件 path.contains(position ) 确保触摸只覆盖路径部分。

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);
  }
}

关于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.

我在这里回答了一个类似的问题:Flutter: What is the correct way to detect touch enter, move and exit on CustomPainter objects

关于flutter - 如何使用路径剪辑 GestureDetector(或 InkWell)输入区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56829473/

相关文章:

firebase - 如何在 Crashlytics/Flutter (Android) 中查看 Dart 代码堆栈跟踪而不是 Java 代码堆栈跟踪

flutter - 映射字段运行时检查是否有问题?

flutter - 来自 Flutter Web 的 HTTP Post 请求

flutter - 警报对话框在我的 flutter torch 项目中不起作用

Flutter 提供者不更新 UI

flutter - 我怎样才能用 Flutter markdown 证明文本的合理性?

Flutter 在换行小部件内垂直对齐文本

dart - 当 Flutter 的 TabBar 被点击时移除高亮

flutter - 带有 if 语句的 getter 的空安全问题

firebase - 如何从 Firebase 实时数据库获取数据并使用 Flutter 将其放入列表中?