Get touch position relative to widget

I am trying to create a Flutter widget to set the temperature, which should look like a thermostat knob. I have expanded CustomPainter to draw this on the screen, and now I am trying to adjust the capture function so that the user can rotate it.

I can use the GestureDetector widget to get a callback when the user touches the screen, but I need to know where it is relative to the center of the handle. Unfortunately, the position provided by the GestureDetector is in absolute coordinates, and the canvas works relative to the start of the widget. Is there a way to convert one of these coordinates to another?

This means that I need:

1) The method of obtaining the position of the crane relative to the CustomPainter widget

2) The way to get the absolute position of the CustomPainter widget

I cannot find an API that any of them can provide. Is there such an API?

Context: https://github.com/dgp1130/thermo/blob/master/lib/widgets/temp_picker.dart

The way the rotary thermostat is currently working, but the “center” of touch is actually about halfway above the real center due to the height of the app bar.

thank

+4
source share
1 answer

You can convert global coordinates to local coordinates using the method RenderBox.globalToLocal. To get RenderBox, you can call findRenderObjecton BuildContext.

--- a/lib/widgets/temp_picker.dart
+++ b/lib/widgets/temp_picker.dart
@@ -41,7 +41,12 @@ class _TempPickerState extends State<TempPicker> {
     return new Container(
       constraints: new BoxConstraints.expand(),
       child: new GestureDetector(
-        onPanUpdate: (details) => setState(() => _tapPos = details.globalPosition),
+        onPanUpdate: (details) {
+          setState(() {
+            RenderBox box = context.findRenderObject();
+            _tapPos = box.globalToLocal(details.globalPosition);
+          });
+        },
         child: new CustomPaint(
           painter: new _TempPainter(
             minValue: widget.minValue,

, TempPicker. _tapPos getAngleFromPosition onPanUpdate _TempPainter. , , .

+4

Source: https://habr.com/ru/post/1676209/


All Articles