Trouble drawing rectangle on a canvas using local coordinates- Flutter

Issue

I have 2 screens.

One the first screen I load up an image from the web and have my user draw a rectangle on the image. I am using local position from onPanStart and onPanUpdate callbacks in the GestureDetector. I am saving the start and end Offset values.

final taggableImage = GestureDetector(
  onPanStart: (DragStartDetails details){
    provider.updateRectangleStart(details.localPosition);
  },
  onPanUpdate: (DragUpdateDetails details ){
    provider.updateRectangleEnd(details.localPosition);
  },
  child: CustomPaint(
    foregroundPainter: provider.drawRect,
    child: image,
  ),
);

Screenshot of drawing the rectangle on the first screen:
enter image description here

Now I would like to load up the images again in a new screen and draw the rectangle back onto the image from the Offset values I have saved earlier. But the rectangle always shows up in the wrong spot and sometimes even outside the image.

Here is how I am redrawing the rectangle from the saved Offset values.

final image = CustomPaint(
  foregroundPainter:  DrawRectangleService(provider.selectedDetection?.detectionRect ?? Rect.zero),
  child: FittedBox(
    fit: BoxFit.fill,
    child: CachedNetworkImage(
      placeholder: (context, url) => loadingWidget("Loading image"),
      imageUrl: imageURL,
    ),
  ),
);

Screenshot of how it looks like when I redraw the rectangle
enter image description here
Question: How do I use the Offset values I saved on my first screen to redraw the rectangle on the image in my second screen.

Solution

convert your coordinates to double, in the range of 0 to 1, both the width and height by dividing them with original width and height of the Image widget,
on the new screen multiply them back with the new width and height of the Image widget.

Answered By – Yadu

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *