Auto Scale Text Size

前端 未结 3 1607
情书的邮戳
情书的邮戳 2021-01-02 09:06

I\'m looking for a way to when I change a screen size it will proportionally resize the text. Currently I tried Auto Scale TextView Text to Fit within Bounds but it doesn\'

3条回答
  •  难免孤独
    2021-01-02 09:35

    You don't need to call AutoResizeTextView test, you can say TextView since the class extends TextView. I don't see why you'd need to call resizeText() either.

    Either way, here's a custom class I like to use to auto re-size text.

    public class AutoFitTextView extends TextView {
    
    public AutoFitTextView(Context context) {
        super(context);
        init();
    }
    
    public AutoFitTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    
    private void init() {
    
        maxTextSize = this.getTextSize();
        if (maxTextSize < 35) {
            maxTextSize = 30;
        }
        minTextSize = 20;
    }
    
    private void refitText(String text, int textWidth) {
        if (textWidth > 0) {
            int availableWidth = textWidth - this.getPaddingLeft()
                    - this.getPaddingRight();
            float trySize = maxTextSize;
    
            this.setTextSize(TypedValue.COMPLEX_UNIT_PX, trySize);
            while ((trySize > minTextSize)
                    && (this.getPaint().measureText(text) > availableWidth)) {
                trySize -= 1;
                if (trySize <= minTextSize) {
                    trySize = minTextSize;
                    break;
                }
                this.setTextSize(TypedValue.COMPLEX_UNIT_PX, trySize);
            }
            this.setTextSize(TypedValue.COMPLEX_UNIT_PX, trySize);
        }
    }
    
    @Override
    protected void onTextChanged(final CharSequence text, final int start,
            final int before, final int after) {
        refitText(text.toString(), this.getWidth());
    }
    
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        if (w != oldw) {
            refitText(this.getText().toString(), w);
        }
    }
    
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
        refitText(this.getText().toString(), parentWidth);
    }
    
    public float getMinTextSize() {
        return minTextSize;
    }
    
    public void setMinTextSize(int minTextSize) {
        this.minTextSize = minTextSize;
    }
    
    public float getMaxTextSize() {
        return maxTextSize;
    }
    
    public void setMaxTextSize(int minTextSize) {
        this.maxTextSize = minTextSize;
    }
    
    private float minTextSize;
    private float maxTextSize;
    
    }
    

提交回复
热议问题