Gettextbounds in android

后端 未结 4 1608
生来不讨喜
生来不讨喜 2020-12-13 16:20

We used to find the rectangle which fits the given text, for example if give \"TESTING\" in gettextbounds api it will give a rectangle that fits the given string \"TESTING\"

4条回答
  •  孤街浪徒
    2020-12-13 16:48

    My solution:

    class Pos {
      public int X;
      public int Y;
    }
    public static void getTextPositionAndRealBound(Paint paint, String text, int x, int y, Pos pos, Rect bound) {
      paint.getTextBounds(text, 0, text.length(), bound);
      // in X
      bound.left = x;
      bound.right = (int)(paint.measureText(text) + 0.5); // .5f to 1
    
      // in Y
      y = y - bound.top;
      bound.top = y;
      bound.bottom = bound.height();
    
      // reset the position
      pos.X = x;
      pos.Y = y;
    }
    

    You know that the X is right and the Y is down in the coord of the bound by getTextBounds.

    The solution can get the position and real bound of text. You can move the text to any position, just edit the var - pos and use it when call Canvas.drawText like this:

    Pos pos;
    Rect bound;
    getTextPositionAndRealBound(paint, text, x, y, pos, bound);
    canvas.drawText(text, pos.X, pos.Y, paint);
    

    Note: thanks for @ToolmakerSteve advice

提交回复
热议问题