Java Code Examples for android.text.TextPaint.measureText()

The following are Jave code examples for showing how to use measureText() of the android.text.TextPaint class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: android-slidr   File: Sushi.java   Source Code and License Vote up 6 votes
private void drawIndicatorsTextAbove(Canvas canvas, String text, TextPaint paintText, float x, float y, Layout.Alignment alignment) {

        final float textHeight = calculateTextMultilineHeight(text, paintText);
        y -= textHeight;

        final int width = (int) paintText.measureText(text);
        if (x >= getWidth() - settings.paddingCorners) {
            x = (getWidth() - width - settings.paddingCorners / 2f);
        } else if (x <= 0) {
            x = width / 2f;
        } else {
            x = (x - width / 2f);
        }

        if (x < 0) {
            x = 0;
        }

        if (x + width > getWidth()) {
            x = getWidth() - width;
        }

        drawText(canvas, text, x, y, paintText, alignment);
    }
 
Example 2
Project: android-slidr   File: Slidr.java   Source Code and License Vote up 6 votes
private void drawIndicatorsTextAbove(Canvas canvas, String text, TextPaint paintText, float x, float y, Layout.Alignment alignment) {

        final float textHeight = calculateTextMultilineHeight(text, paintText);
        y -= textHeight;

        final int width = (int) paintText.measureText(text);
        if (x >= getWidth() - settings.paddingCorners) {
            x = (getWidth() - width - settings.paddingCorners / 2f);
        } else if (x <= 0) {
            x = width / 2f;
        } else {
            x = (x - width / 2f);
        }

        if (x < 0) {
            x = 0;
        }

        if (x + width > getWidth()) {
            x = getWidth() - width;
        }

        drawText(canvas, text, x, y, paintText, alignment);
    }
 
Example 3
Project: meipai-Android   File: StringUtils.java   Source Code and License Vote up 5 votes
/** 获取字符串宽度 */
public static float GetTextWidth(String Sentence, float Size) {
	if (isEmpty(Sentence))
		return 0;
	TextPaint FontPaint = new TextPaint();
	FontPaint.setTextSize(Size);
	return FontPaint.measureText(Sentence.trim()) + (int) (Size * 0.1); // 留点余地
}
 
Example 4
Project: BilibiliClient   File: RegionTypeDetailsActivity.java   Source Code and License Vote up 5 votes
public void measureTabLayoutTextWidth(int position) {

    String titleName = titles.get(position);
    TextView titleView = mSlidingTab.getTitleView(position);
    TextPaint paint = titleView.getPaint();
    float v = paint.measureText(titleName);
    mSlidingTab.setIndicatorWidth(v / 3);
  }
 
Example 5
Project: SimpleRssReader   File: RoundedCornersBackgroundSpan.java   Source Code and License Vote up 5 votes
/**
 * Update list of holders on line.
 *
 * @param backgroundHolder holder of text part
 * @param startInText      start position in text
 * @param endInText        end position in text
 */
private void updateHoldersOnLine(@NonNull Paint p, int left, int right, int top, int baseline,
                                 @NonNull CharSequence text, @NonNull BackgroundHolder backgroundHolder,
                                 int startInText, int endInText) {
    final TextPaint textPaint = getTextPaint(p, text, startInText, endInText);
    final float prevTextWidth = getPrevTextWidth(text);
    float curTextWidth;
    try {
        curTextWidth = textPaint.measureText(text, startInText, endInText);
    } catch (IndexOutOfBoundsException e) {
        // skip drawing. This crashes on Android 4.3 (potentially on all 4.x) devices
        // without `continue` it will draw an empty rectangle with rounded corners (if padding has been set)
        return;
    }
    float l = left;
    float r = right;
    if (mRtlText) {
        r -= prevTextWidth;
        l = r - curTextWidth;
    } else {
        l += prevTextWidth;
        r = l + curTextWidth;
    }
    final float rectLeft = l - mPadding;
    final float rectTop = top - mPadding;
    final float rectRight = r + mPadding;
    final float rectBottom = baseline + p.descent() + mPadding;
    final LineDataHolder lineDataHolder = new LineDataHolder.Builder()
            .setTextPaint(textPaint)
            .setStartIntText(startInText)
            .setEndIntText(endInText)
            .setLeft(rectLeft)
            .setRight(rectRight)
            .setTop(rectTop)
            .setBottom(rectBottom)
            .setBgHolder(backgroundHolder)
            .build();
    mHoldersOnLine.add(lineDataHolder);
}
 
Example 6
Project: android-slidr   File: Sushi.java   Source Code and License Vote up 5 votes
private void drawText(Canvas canvas, String text, float x, float y, TextPaint paint, Layout.Alignment aligment) {
    canvas.save();
    {
        canvas.translate(x, y);
        final StaticLayout staticLayout = new StaticLayout(text, paint, (int) paint.measureText(text), aligment, 1.0f, 0, false);
        staticLayout.draw(canvas);
    }
    canvas.restore();
}
 
Example 7
Project: BilibiliClient   File: RegionTypeDetailsActivity.java   Source Code and License Vote up 5 votes
private void measureTabLayoutTextWidth(int position) {
    String title = mTitles.get(position);
    TextView titleView = mSlidingTab.getTitleView(position);
    TextPaint paint = titleView.getPaint();
    float width = paint.measureText(title);
    mSlidingTab.setIndicatorWidth(width / 3);
}
 
Example 8
Project: BilibiliClient   File: VideoDetailsActivity.java   Source Code and License Vote up 5 votes
private void measureTabLayoutTextWidth(int position) {
    String title = mTitles.get(position);
    TextView titleView = mSlidingTabLayout.getTitleView(position);
    TextPaint paint = titleView.getPaint();
    float textWidth = paint.measureText(title);
    mSlidingTabLayout.setIndicatorWidth(textWidth / 3);
}
 
Example 9
Project: CurveView   File: CurveView.java   Source Code and License Vote up 5 votes
private int getTextOffsetX(TextPaint paint, String s, int gravity) {
    int width = (int) paint.measureText(s);
    int offset = 0;
    if ((gravity & Gravity.CENTER_HORIZONTAL) != 0) {
        offset = - width / 2;
    } else if ((gravity & Gravity.START) != 0) {
        offset = - width;
    }

    return offset;
}
 
Example 10
Project: android-slidr   File: Sushi.java   Source Code and License Vote up 5 votes
private void drawMultilineText(Canvas canvas, String text, float x, float y, TextPaint paint, Layout.Alignment aligment) {
    final float lineHeight = paint.getTextSize();
    float lineY = y;
    for (CharSequence line : text.split("\n")) {
        canvas.save();
        {
            final float lineWidth = (int) paint.measureText(line.toString());
            float lineX = x;
            if (aligment == Layout.Alignment.ALIGN_CENTER) {
                lineX -= lineWidth / 2f;
            }
            if (lineX < 0) {
                lineX = 0;
            }

            final float right = lineX + lineWidth;
            if (right > canvas.getWidth()) {
                lineX = canvas.getWidth() - lineWidth - settings.paddingCorners;
            }

            canvas.translate(lineX, lineY);
            final StaticLayout staticLayout = new StaticLayout(line, paint, (int) lineWidth, aligment, 1.0f, 0, false);
            staticLayout.draw(canvas);

            lineY += lineHeight;
        }
        canvas.restore();
    }

}
 
Example 11
Project: PaoMovie   File: StringUtils.java   Source Code and License Vote up 5 votes
/** 获取字符串宽度 */
public static float GetTextWidth(String Sentence, float Size) {
	if (isEmpty(Sentence))
		return 0;
	TextPaint FontPaint = new TextPaint();
	FontPaint.setTextSize(Size);
	return FontPaint.measureText(Sentence.trim()) + (int) (Size * 0.1); // 留点余地
}
 
Example 12
Project: Pocket-Plays-for-Twitch   File: FontFitTextView.java   Source Code and License Vote up 4 votes
/**
 * Resize the text size with specified width and height
 * @param width
 * @param height
 */
public void resizeText(int width, int height) {
	CharSequence text = getText();
	// Do not resize if the view does not have dimensions or there is no text
	if (text == null || text.length() == 0 || height <= 0 || width <= 0 || mTextSize == 0) {
		return;
	}

	if (getTransformationMethod() != null) {
		text = getTransformationMethod().getTransformation(text, this);
	}

	// Get the text view's paint object
	TextPaint textPaint = getPaint();

	// Store the current text size
	float oldTextSize = textPaint.getTextSize();
	// If there is a max text size set, use the lesser of that and the default text size
	float targetTextSize = mMaxTextSize > 0 ? Math.min(mTextSize, mMaxTextSize) : mTextSize;

	// Get the required text height
	int textHeight = getTextHeight(text, textPaint, width, targetTextSize);

	// Until we either fit within our text view or we had reached our min text size, incrementally try smaller sizes
	while (textHeight > height && targetTextSize > mMinTextSize) {
		targetTextSize = Math.max(targetTextSize - 2, mMinTextSize);
		textHeight = getTextHeight(text, textPaint, width, targetTextSize);
	}

	// If we had reached our minimum text size and still don't fit, append an ellipsis
	if (mAddEllipsis && targetTextSize == mMinTextSize && textHeight > height) {
		// Draw using a static layout
		// modified: use a copy of TextPaint for measuring
		TextPaint paint = new TextPaint(textPaint);
		// Draw using a static layout
		StaticLayout layout = new StaticLayout(text, paint, width, Layout.Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, false);
		// Check that we have a least one line of rendered text
		if (layout.getLineCount() > 0) {
			// Since the line at the specific vertical position would be cut off,
			// we must trim up to the previous line
			int lastLine = layout.getLineForVertical(height) - 1;
			// If the text would not even fit on a single line, clear it
			if (lastLine < 0) {
				setText("");
			}
			// Otherwise, trim to the previous line and add an ellipsis
			else {
				int start = layout.getLineStart(lastLine);
				int end = layout.getLineEnd(lastLine);
				float lineWidth = layout.getLineWidth(lastLine);
				float ellipseWidth = textPaint.measureText(mEllipsis);

				// Trim characters off until we have enough room to draw the ellipsis
				while (width < lineWidth + ellipseWidth) {
					lineWidth = textPaint.measureText(text.subSequence(start, --end + 1).toString());
				}
				setText(text.subSequence(0, end) + mEllipsis);
			}
		}
	}

	// Some devices try to auto adjust line spacing, so force default line spacing
	// and invalidate the layout as a side effect
	setTextSize(TypedValue.COMPLEX_UNIT_PX, targetTextSize);
	setLineSpacing(mSpacingAdd, mSpacingMult);

	// Notify the listener if registered
	if (mTextResizeListener != null) {
		mTextResizeListener.onTextResize(this, oldTextSize, targetTextSize);
	}

	// Reset force resize flag
	mNeedsResize = false;
}
 
Example 13
Project: stynico   File: AutofitHelper.java   Source Code and License Vote up 4 votes
/**
    * Re-sizes the textSize of the TextView so that the text fits within the bounds of the View.
    */
   private static void autofit(AppCompatTextView view, TextPaint paint, float minTextSize, float maxTextSize,
							int maxLines, float precision)
{
       if (maxLines <= 0 || maxLines == Integer.MAX_VALUE)
	{
           // Don't auto-size since there's no limit on lines.
           return;
       }

       int targetWidth = view.getWidth() - view.getPaddingLeft() - view.getPaddingRight();
       if (targetWidth <= 0)
	{
           return;
       }

       CharSequence text = view.getText();
       TransformationMethod method = view.getTransformationMethod();
       if (method != null)
	{
           text = method.getTransformation(text, view);
       }

       Context context = view.getContext();
       Resources r = Resources.getSystem();
       DisplayMetrics displayMetrics;

       float size = maxTextSize;
       float high = size;
       float low = 0;

       if (context != null)
	{
           r = context.getResources();
       }
       displayMetrics = r.getDisplayMetrics();

       paint.set(view.getPaint());
       paint.setTextSize(size);

       if ((maxLines == 1 && paint.measureText(text, 0, text.length()) > targetWidth)
		|| getLineCount(text, paint, size, targetWidth, displayMetrics) > maxLines)
	{
           size = getAutofitTextSize(text, paint, targetWidth, maxLines, low, high, precision,
								  displayMetrics);
       }

       if (size < minTextSize)
	{
           size = minTextSize;
       }

       view.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
   }
 
Example 14
Project: Flashcard-Maker-Android   File: AutoResizeTextView.java   Source Code and License Vote up 4 votes
/**
 * Resize the text size with specified width and height
 * @param width
 * @param height
 */
public void resizeText(int width, int height) {
    CharSequence text = getText();
    // Do not resize if the view does not have dimensions or there is no text
    if (text == null || text.length() == 0 || height <= 0 || width <= 0 || mTextSize == 0) {
        return;
    }

    if (getTransformationMethod() != null) {
        text = getTransformationMethod().getTransformation(text, this);
    }

    // Get the text view's paint object
    TextPaint textPaint = getPaint();

    // Store the current text size
    float oldTextSize = textPaint.getTextSize();
    // If there is a max text size set, use the lesser of that and the default text size
    float targetTextSize = mMaxTextSize > 0 ? Math.min(mTextSize, mMaxTextSize) : mTextSize;

    // Get the required text height
    int textHeight = getTextHeight(text, textPaint, width, targetTextSize);

    // Until we either fit within our text view or we had reached our min text size, incrementally try smaller sizes
    while (textHeight > height && targetTextSize > mMinTextSize) {
        targetTextSize = Math.max(targetTextSize - 2, mMinTextSize);
        textHeight = getTextHeight(text, textPaint, width, targetTextSize);
    }

    // If we had reached our minimum text size and still don't fit, append an ellipsis
    if (mAddEllipsis && targetTextSize == mMinTextSize && textHeight > height) {
        // Draw using a static layout
        // modified: use a copy of TextPaint for measuring
        TextPaint paint = new TextPaint(textPaint);
        // Draw using a static layout
        StaticLayout layout = new StaticLayout(text, paint, width, Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, false);
        // Check that we have a least one line of rendered text
        if (layout.getLineCount() > 0) {
            // Since the line at the specific vertical position would be cut off,
            // we must trim up to the previous line
            int lastLine = layout.getLineForVertical(height) - 1;
            // If the text would not even fit on a single line, clear it
            if (lastLine < 0) {
                setText("");
            }
            // Otherwise, trim to the previous line and add an ellipsis
            else {
                int start = layout.getLineStart(lastLine);
                int end = layout.getLineEnd(lastLine);
                float lineWidth = layout.getLineWidth(lastLine);
                float ellipseWidth = textPaint.measureText(mEllipsis);

                // Trim characters off until we have enough room to draw the ellipsis
                while (width < lineWidth + ellipseWidth) {
                    lineWidth = textPaint.measureText(text.subSequence(start, --end + 1).toString());
                }
                setText(text.subSequence(0, end) + mEllipsis);
            }
        }
    }

    // Some devices try to auto adjust line spacing, so force default line spacing
    // and invalidate the layout as a side effect
    setTextSize(TypedValue.COMPLEX_UNIT_PX, targetTextSize);
    setLineSpacing(mSpacingAdd, mSpacingMult);

    // Notify the listener if registered
    if (mTextResizeListener != null) {
        mTextResizeListener.onTextResize(this, oldTextSize, targetTextSize);
    }

    // Reset force resize flag
    mNeedsResize = false;
}
 
Example 15
Project: DarkCalculator   File: AutofitHelper.java   Source Code and License Vote up 4 votes
/**
 * Re-sizes the textSize of the TextView so that the text fits within the bounds of the View.
 */
private static void autofit(TextView view, TextPaint paint, float minTextSize, float maxTextSize,
                            int maxLines, float precision) {
    if (maxLines <= 0 || maxLines == Integer.MAX_VALUE) {
        // Don't auto-size since there's no limit on lines.
        return;
    }

    int targetWidth = view.getWidth() - view.getPaddingLeft() - view.getPaddingRight();
    if (targetWidth <= 0) {
        return;
    }

    CharSequence text = view.getText();
    TransformationMethod method = view.getTransformationMethod();
    if (method != null) {
        text = method.getTransformation(text, view);
    }

    Context context = view.getContext();
    Resources r = Resources.getSystem();
    DisplayMetrics displayMetrics;

    float size = maxTextSize;
    float high = size;
    float low = 0;

    if (context != null) {
        r = context.getResources();
    }
    displayMetrics = r.getDisplayMetrics();

    paint.set(view.getPaint());
    paint.setTextSize(size);

    if ((maxLines == 1 && paint.measureText(text, 0, text.length()) > targetWidth)
            || getLineCount(text, paint, size, targetWidth, displayMetrics) > maxLines) {
        size = getAutofitTextSize(text, paint, targetWidth, maxLines, low, high, precision,
                displayMetrics);
    }

    if (size < minTextSize) {
        size = minTextSize;
    }

    view.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
}
 
Example 16
Project: QMUI_Android   File: QMUIVerticalTextView.java   Source Code and License Vote up 4 votes
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onDraw(Canvas canvas) {
        if (!mIsVerticalMode) {
            super.onDraw(canvas);
        } else {
            if (mLineCount == 0) {
                return;
            }

            final TextPaint paint = getPaint();
            paint.setColor(getCurrentTextColor());
            paint.drawableState = getDrawableState();
            final Paint.FontMetricsInt fontMetricsInt = paint.getFontMetricsInt();
            final char[] chars = getText().toString().toCharArray();

            canvas.save();

            int curLine = 0;
            float curLineX = getWidth() - getPaddingRight() - mLineWidths[curLine];
            float curX = curLineX;
            float curY = getPaddingTop();
            for (int i = 0; i < chars.length; i++) {
                final char c = chars[i];
//            boolean needRotate = !Caches.isCJK(c);
                boolean needRotate = !isCJKCharacter(c);
                final int saveCount = canvas.save();
                if (needRotate) {
                    canvas.rotate(90, curX, curY);
                }
                // draw
                float textX = curX;
                float textBaseline = needRotate ?
                        curY - (mLineWidths[curLine] - (fontMetricsInt.bottom - fontMetricsInt.top)) / 2 - fontMetricsInt.descent :
                        curY - fontMetricsInt.ascent;
                canvas.drawText(chars, i, 1, textX, textBaseline, paint);
                canvas.restoreToCount(saveCount);

                // if break line
                boolean hasNextChar = i + 1 < chars.length;
                if (hasNextChar) {
//                boolean breakLine = needBreakLine(i, mLineCharsCount, curLine);
                    boolean nextCharBreakLine = i + 1 > mLineBreakIndex[curLine];
                    if (nextCharBreakLine && curLine + 1 < mLineWidths.length) {
                        // new line
                        curLine++;
                        curLineX -= (mLineWidths[curLine] * getLineSpacingMultiplier() + getLineSpacingExtra());
                        curX = curLineX;
                        curY = getPaddingTop();
                    } else {
                        // move to next char
                        if (needRotate) {
                            curY += paint.measureText(chars, i, 1);
                        } else {
                            curY += fontMetricsInt.descent - fontMetricsInt.ascent;
                        }
                    }
                }
            }

            canvas.restore();
        }
    }
 
Example 17
Project: LuaViewPlayground   File: AutofitHelper.java   Source Code and License Vote up 4 votes
/**
 * Re-sizes the textSize of the TextView so that the text fits within the bounds of the View.
 */
private static void autofit(TextView view, TextPaint paint, float minTextSize, float maxTextSize,
                            int maxLines, float precision) {
    if (maxLines <= 0 || maxLines == Integer.MAX_VALUE) {
        // Don't auto-size since there's no limit on lines.
        return;
    }

    int targetWidth = view.getWidth() - view.getPaddingLeft() - view.getPaddingRight();
    if (targetWidth <= 0) {
        return;
    }

    CharSequence text = view.getText();
    TransformationMethod method = view.getTransformationMethod();
    if (method != null) {
        text = method.getTransformation(text, view);
    }

    Context context = view.getContext();
    Resources r = Resources.getSystem();
    DisplayMetrics displayMetrics;

    float size = maxTextSize;
    float high = size;
    float low = 0;

    if (context != null) {
        r = context.getResources();
    }
    displayMetrics = r.getDisplayMetrics();

    paint.set(view.getPaint());
    paint.setTextSize(size);

    if ((maxLines == 1 && paint.measureText(text, 0, text.length()) > targetWidth)
            || getLineCount(text, paint, size, targetWidth, displayMetrics) > maxLines) {
        size = getAutofitTextSize(text, paint, targetWidth, maxLines, low, high, precision,
                displayMetrics);
    }

    if (size < minTextSize) {
        size = minTextSize;
    }

    view.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
}
 
Example 18
Project: quidditchtimekeeper   File: AutoResizeTextView.java   Source Code and License Vote up 4 votes
/**
 * Resize the text size with specified width and height
 * @param width
 * @param height
 */
public void resizeText(int width, int height) {
    CharSequence text = getText();
    // Do not resize if the view does not have dimensions or there is no text
    if (text == null || text.length() == 0 || height <= 0 || width <= 0 || mTextSize == 0) {
        return;
    }

    if (getTransformationMethod() != null) {
        text = getTransformationMethod().getTransformation(text, this);
    }

    // Get the text view's paint object
    TextPaint textPaint = getPaint();

    // Store the current text size
    float oldTextSize = textPaint.getTextSize();
    // If there is a max text size set, use the lesser of that and the default text size
    float targetTextSize = mMaxTextSize > 0 ? Math.min(mTextSize, mMaxTextSize) : mTextSize;

    // Get the required text height
    int textHeight = getTextHeight(text, textPaint, width, targetTextSize);

    // Until we either fit within our text view or we had reached our min text size, incrementally try smaller sizes
    while (textHeight > height && targetTextSize > mMinTextSize) {
        targetTextSize = Math.max(targetTextSize - 2, mMinTextSize);
        textHeight = getTextHeight(text, textPaint, width, targetTextSize);
    }

    // If we had reached our minimum text size and still don't fit, append an ellipsis
    if (mAddEllipsis && targetTextSize == mMinTextSize && textHeight > height) {
        // Draw using a static layout
        // modified: use a copy of TextPaint for measuring
        TextPaint paint = new TextPaint(textPaint);
        // Draw using a static layout
        StaticLayout layout = new StaticLayout(text, paint, width, Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, false);
        // Check that we have a least one line of rendered text
        if (layout.getLineCount() > 0) {
            // Since the line at the specific vertical position would be cut off,
            // we must trim up to the previous line
            int lastLine = layout.getLineForVertical(height) - 1;
            // If the text would not even fit on a single line, clear it
            if (lastLine < 0) {
                setText("");
            }
            // Otherwise, trim to the previous line and add an ellipsis
            else {
                int start = layout.getLineStart(lastLine);
                int end = layout.getLineEnd(lastLine);
                float lineWidth = layout.getLineWidth(lastLine);
                float ellipseWidth = textPaint.measureText(mEllipsis);

                // Trim characters off until we have enough room to draw the ellipsis
                while (width < lineWidth + ellipseWidth) {
                    lineWidth = textPaint.measureText(text.subSequence(start, --end + 1).toString());
                }
                setText(text.subSequence(0, end) + mEllipsis);
            }
        }
    }

    // Some devices try to auto adjust line spacing, so force default line spacing
    // and invalidate the layout as a side effect
    setTextSize(TypedValue.COMPLEX_UNIT_PX, targetTextSize);
    setLineSpacing(mSpacingAdd, mSpacingMult);

    // Notify the listener if registered
    if (mTextResizeListener != null) {
        mTextResizeListener.onTextResize(this, oldTextSize, targetTextSize);
    }

    // Reset force resize flag
    mNeedsResize = false;
}
 
Example 19
Project: DailyStudy   File: MyTextView.java   Source Code and License Vote up 4 votes
public MyTextView(final Context context, final AttributeSet attrs, 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, final RectF availableSpace) {
            _paint.setTextSize(suggestedSize);
            final TransformationMethod transformationMethod = getTransformationMethod();
            final String text;
            if (transformationMethod != null)
                text = transformationMethod.getTransformation(getText(), MyTextView.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), text.charAt(end)))
                        return 1;
                    if (maxWidth < layout.getLineRight(i) - layout.getLineLeft(i))
                        maxWidth = (int) layout.getLineRight(i) - (int) layout.getLineLeft(i);
                }
                //for (int i = 0; i < layout.getLineCount(); i++)
                //    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;
}
 
Example 20
Project: android-autofittextview   File: AutofitHelper.java   Source Code and License Vote up 4 votes
/**
 * Re-sizes the textSize of the TextView so that the text fits within the bounds of the View.
 */
private static void autofit(TextView view, TextPaint paint, float minTextSize, float maxTextSize,
        int maxLines, float precision) {
    if (maxLines <= 0 || maxLines == Integer.MAX_VALUE) {
        // Don't auto-size since there's no limit on lines.
        return;
    }

    int targetWidth = view.getWidth() - view.getPaddingLeft() - view.getPaddingRight();
    if (targetWidth <= 0) {
        return;
    }

    CharSequence text = view.getText();
    TransformationMethod method = view.getTransformationMethod();
    if (method != null) {
        text = method.getTransformation(text, view);
    }

    Context context = view.getContext();
    Resources r = Resources.getSystem();
    DisplayMetrics displayMetrics;

    float size = maxTextSize;
    float high = size;
    float low = 0;

    if (context != null) {
        r = context.getResources();
    }
    displayMetrics = r.getDisplayMetrics();

    paint.set(view.getPaint());
    paint.setTextSize(size);

    if ((maxLines == 1 && paint.measureText(text, 0, text.length()) > targetWidth)
            || getLineCount(text, paint, size, targetWidth, displayMetrics) > maxLines) {
        size = getAutofitTextSize(text, paint, targetWidth, maxLines, low, high, precision,
                displayMetrics);
    }

    if (size < minTextSize) {
        size = minTextSize;
    }

    view.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
}