Ejemplo n.º 1
0
  /**
   * 通过x轴间距,计算出字体大小,自动适应宽度
   *
   * @param paint the Paint to set the text size for
   * @param desiredWidth the desired width
   * @param text the text that should be that width
   * @return
   */
  private void setTextSizeForWidth(Paint paint, float desiredWidth, String text) {

    // Pick a reasonably large value for the test. Larger values produce
    // more accurate results, but may cause problems with hardware
    // acceleration. But there are workarounds for that, too; refer to
    // http://stackoverflow.com/questions/6253528/font-size-too-large-to-fit-in-cache
    final float testTextSize = 48f;

    // Get the bounds of the text, using our testTextSize.
    paint.setTextSize(testTextSize);
    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, text.length(), bounds);

    // Calculate the desired size as a proportion of our testTextSize.
    float desiredTextSize = testTextSize * desiredWidth / bounds.width();

    // 如果计算出的字体高度小于预设值
    if (bottomTextSize > desiredTextSize) {
      // Set the paint for that size.
      paint.setTextSize(desiredTextSize);
    } else {
      paint.setTextSize(bottomTextSize);
    }
  }