How to know if Offset is inside circle

Viewed 1200

In my code I have CircleAvatar with border. I want to know if user tap exactly on border. For this I need to check if tap is inside big circle (Container), but not inside small circle (CircleAvatar). Does anybody know how could I check this?

Widget build(BuildContext context) {
  return Listener(
    child: Container(
      key: key,
      padding: EdgeInsets.all(8.0),
      decoration: ShapeDecoration(shape: CircleBorder(), color: Colors.yellow),
      child: CircleAvatar(
        backgroundImage: NetworkImage(widget.imgSrc),
        radius: 60.0,
      ),
    ),
    onPointerDown: (event) {
      if (renderBox == null) {
        renderBox = key.currentContext?.findRenderObject();
      }
      Rect rect = renderBox.paintBounds;
      // todo ......
    },
  );
}
2 Answers

You should use the Pythagore theorem to check if the Offset is in a circle :

import 'dart:math';

/// check if a [point] is in a circle of a given [radius]
bool isPointInside(Offset point, double radius) =>
  pow(point.dx, 2) + pow(point.dy, 2) < pow(radius, 2);

Do this for the big and small circle and check if the results match what you want.

Edit : removed the sqrt in favour of pow(radius) as suggested by @randal-schwartz

Maybe it's not the best way, but I've found some solution

Rect bigRect = renderBox.paintBounds.shift(renderBox?.localToGlobal(Offset.zero));
Rect smallRect = bigRect.deflate(padding);
Path path = Path()
  ..fillType = PathFillType.evenOdd
  ..addOval(bigRect)
  ..addOval(smallRect);
if (path.contains(event.position)) { // todo...

P.S. Muldec's solution can be used too, it works, but I was looking for another type, like contains

Related