我已经使用 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/