AutoResizeTextView.java 文件源码

java
阅读 31 收藏 0 点赞 0 评论 0

项目:Jisho 作者:
public AutoResizeTextView(@NonNull final Context context, final AttributeSet attrs, @AttrRes final int defStyle) {
    super(context, attrs, defStyle);
    // using the minimal recommended font size
    _minTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics());
    _maxTextSize = getTextSize();
    _paint = new TextPaint(getPaint());
    if (_maxLines == 0)
        // no value was assigned during construction
        _maxLines = NO_LINE_LIMIT;
    // prepare size tester:
    _sizeTester = new SizeTester() {
        final RectF textRect = new RectF();

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public int onTestSize(final int suggestedSize, @NonNull final RectF availableSpace) {
            _paint.setTextSize(suggestedSize);
            final TransformationMethod transformationMethod = getTransformationMethod();
            final String text;
            if (transformationMethod != null)
                text = transformationMethod.getTransformation(getText(), AutoResizeTextView.this).toString();
            else
                text = getText().toString();
            final boolean singleLine = getMaxLines() == 1;
            if (singleLine) {
                textRect.bottom = _paint.getFontSpacing();
                textRect.right = _paint.measureText(text);
            } else {
                final StaticLayout layout = new StaticLayout(text, _paint, _widthLimit, Layout.Alignment.ALIGN_NORMAL, _spacingMult, _spacingAdd, true);
                // return early if we have more lines
                if (getMaxLines() != NO_LINE_LIMIT && layout.getLineCount() > getMaxLines())
                    return 1;
                textRect.bottom = layout.getHeight();
                int maxWidth = -1;
                int lineCount = layout.getLineCount();
                for (int i = 0; i < lineCount; i++) {
                    int end = layout.getLineEnd(i);
                    if (i < lineCount - 1 && end > 0 && !isValidWordWrap(text.charAt(end - 1)))
                        return 1;
                    if (maxWidth < layout.getLineRight(i) - layout.getLineLeft(i))
                        maxWidth = (int) layout.getLineRight(i) - (int) layout.getLineLeft(i);
                }
                textRect.right = maxWidth;
            }
            textRect.offsetTo(0, 0);
            if (availableSpace.contains(textRect))
                // may be too small, don't worry we will find the best match
                return -1;
            // else, too big
            return 1;
        }
    };
    _initialized = true;
}
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号