offsetAt method

int offsetAt(
  1. Offset point
)

Nearest logical text offset to point, or null when the point is outside the run's reach.

Implementation

int offsetAt(Offset point) {
  if (text.isEmpty) return 0;
  if (!hasCharGeometry || !reliable) {
    final double width = rect.width <= 0 ? 1 : rect.width;
    final double t = ((point.dx - rect.left) / width).clamp(0, 1).toDouble();
    final int index = ((rtl ? 1 - t : t) * text.length).floor();
    return index.clamp(0, text.length - 1);
  }
  int best = 0;
  double bestDistance = double.infinity;
  for (int i = 0; i < charRects.length; i++) {
    final Rect piece = charRects[i];
    if (piece.contains(point)) return i;
    final double dx = point.dx < piece.left ? piece.left - point.dx : (point.dx > piece.right ? point.dx - piece.right : 0);
    final double dy = point.dy < piece.top ? piece.top - point.dy : (point.dy > piece.bottom ? point.dy - piece.bottom : 0);
    final double distance = dx * dx + dy * dy;
    if (distance < bestDistance) {
      bestDistance = distance;
      best = i;
    }
  }
  return best;
}