How to adjust text font size to fit textview

后端 未结 22 1735
無奈伤痛
無奈伤痛 2020-11-22 05:15

Is there any way in android to adjust the textsize in a textview to fit the space it occupies?

E.g. I\'m using a TableLayout and adding several Te

22条回答
  •  孤独总比滥情好
    2020-11-22 05:51

    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);
      }
    

提交回复
热议问题