Auto Scale TextView Text to Fit within Bounds

后端 未结 30 2914
囚心锁ツ
囚心锁ツ 2020-11-21 05:49

I\'m looking for an optimal way to resize wrapping text in a TextView so that it will fit within its getHeight and getWidth bounds. I\'m not simply looking for

30条回答
  •  眼角桃花
    2020-11-21 05:50

    Extend TextView and override onDraw with the code below. It will keep text aspect ratio but size it to fill the space. You could easily modify code to stretch if necessary.

      @Override
      protected void onDraw(@NonNull Canvas canvas) {
        TextPaint textPaint = getPaint();
        textPaint.setColor(getCurrentTextColor());
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.drawableState = getDrawableState();
    
        String text = getText().toString();
        float desiredWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - 2;
        float desiredHeight = getMeasuredHeight() - getPaddingTop() - getPaddingBottom() - 2;
        float textSize = textPaint.getTextSize();
    
        for (int i = 0; i < 10; i++) {
          textPaint.getTextBounds(text, 0, text.length(), rect);
          float width = rect.width();
          float height = rect.height();
    
          float deltaWidth = width - desiredWidth;
          float deltaHeight = height - desiredHeight;
    
          boolean fitsWidth = deltaWidth <= 0;
          boolean fitsHeight = deltaHeight <= 0;
    
          if ((fitsWidth && Math.abs(deltaHeight) < 1.0)
              || (fitsHeight && Math.abs(deltaWidth) < 1.0)) {
            // close enough
            break;
          }
    
          float adjustX = desiredWidth / width;
          float adjustY = desiredHeight / height;
    
          textSize = textSize * (adjustY < adjustX ? adjustY : adjustX);
    
          // adjust text size
          textPaint.setTextSize(textSize);
        }
        float x = desiredWidth / 2f;
        float y = desiredHeight / 2f - rect.top - rect.height() / 2f;
        canvas.drawText(text, x, y, textPaint);
      }
    

提交回复
热议问题