android.text.TextPaint#getTextSize ( )源码实例Demo

下面列出了android.text.TextPaint#getTextSize ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: ChipsLibrary   文件: RecipientEditTextView.java
private DrawableRecipientChip constructChipSpan(final RecipientEntry contact,final boolean pressed,final boolean leaveIconSpace) throws NullPointerException
{
if(mChipBackground==null)
  throw new NullPointerException("Unable to render any chips as setChipDimensions was not called.");
final TextPaint paint=getPaint();
final float defaultSize=paint.getTextSize();
final int defaultColor=paint.getColor();
Bitmap tmpBitmap;
if(pressed)
  tmpBitmap=createSelectedChip(contact,paint);
else tmpBitmap=createUnselectedChip(contact,paint,leaveIconSpace);
// Pass the full text, un-ellipsized, to the chip.
final Drawable result=new BitmapDrawable(getResources(),tmpBitmap);
result.setBounds(0,0,tmpBitmap.getWidth(),tmpBitmap.getHeight());
final DrawableRecipientChip recipientChip=new VisibleRecipientChip(result,contact);
// Return text to the original size.
paint.setTextSize(defaultSize);
paint.setColor(defaultColor);
return recipientChip;
}
 
源代码2 项目: DSAvataImageView   文件: DSAvatarImageView.java
private float getTextSizeToFit(int maxWidth,int maxHeight,String input,TextPaint textPaint){
	float textSize = textPaint.getTextSize();
	String text=getTextForSize(input);
	if(text.length()==0)
		return textSize;


	Rect textBound = new Rect();
	textPaint.getTextBounds(text, 0, text.length(), textBound);
	float width = textBound.width();
    float height = textBound.height();
    float adjustX = maxWidth / width;
    float adjustY = maxHeight / height;
    textSize = textSize * (adjustY < adjustX ? adjustY : adjustX);



	return textSize;
}
 
源代码3 项目: android-slidr   文件: Sushi.java
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();
    }

}
 
源代码4 项目: advanced-textview   文件: RainbowSpanActivity.java
@Override
public void updateDrawState(TextPaint paint) {
  paint.setStyle(Paint.Style.FILL);
  Shader shader = new LinearGradient(0, 0, 0, paint.getTextSize() * colors.length, colors, null,
      Shader.TileMode.MIRROR);
  Matrix matrix = new Matrix();
  matrix.setRotate(90);
  shader.setLocalMatrix(matrix);
  paint.setShader(shader);
}
 
private float findNewTextSize(int width, int height, CharSequence text) {
    TextPaint textPaint = new TextPaint(getPaint());

    float targetTextSize = textPaint.getTextSize();

    int textHeight = getTextHeight(text, textPaint, width, targetTextSize);
    while(textHeight > height && targetTextSize > mMinTextSize) {
        targetTextSize = Math.max(targetTextSize - 1, mMinTextSize);
        textHeight = getTextHeight(text, textPaint, width, targetTextSize);
    }
    return targetTextSize;
}
 
private float findNewTextSize(int width, int height, CharSequence text) {
    TextPaint textPaint = new TextPaint(getPaint());

    float targetTextSize = textPaint.getTextSize();

    int textHeight = getTextHeight(text, textPaint, width, targetTextSize);
    while(textHeight > height && targetTextSize > mMinTextSize) {
        targetTextSize = Math.max(targetTextSize - 1, mMinTextSize);
        textHeight = getTextHeight(text, textPaint, width, targetTextSize);
    }
    return targetTextSize;
}
 
private float findNewTextSize(int width, int height, CharSequence text) {
	TextPaint textPaint = new TextPaint(getPaint());

	float targetTextSize = textPaint.getTextSize();

	int textHeight = getTextHeight(text, textPaint, width, targetTextSize);
	while(textHeight > height && targetTextSize > mMinTextSize) {
		targetTextSize = Math.max(targetTextSize - 1, mMinTextSize);
		textHeight = getTextHeight(text, textPaint, width, targetTextSize);
	}
	return targetTextSize;
}
 
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void updateDrawState(TextPaint paint) {
	paint.setStyle(Paint.Style.FILL);
	Shader shader = new LinearGradient(0, 0, 0, paint.getTextSize()
			* colors.length, colors, null, Shader.TileMode.MIRROR);
	Matrix matrix = new Matrix();
	matrix.setRotate(90);
	shader.setLocalMatrix(matrix);
	paint.setShader(shader);
}
 
@Override
public void updateDrawState(TextPaint paint) {
	paint.setStyle(Paint.Style.FILL);
	Shader shader = new LinearGradient(0, 0, 0, paint.getTextSize()
			* colors.length, colors, null, Shader.TileMode.MIRROR);
	Matrix matrix = new Matrix();
	matrix.setRotate(90);
	shader.setLocalMatrix(matrix);
	paint.setShader(shader);
}
 
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void updateDrawState(TextPaint paint) {
	paint.setStyle(Paint.Style.FILL);
	Shader shader = new LinearGradient(0, 0, 0, paint.getTextSize()
			* colors.length, colors, null, Shader.TileMode.MIRROR);
	Matrix matrix = new Matrix();
	matrix.setRotate(90);
	shader.setLocalMatrix(matrix);
	paint.setShader(shader);
}
 
源代码11 项目: Twire   文件: FontFitTextView.java
/**
 * 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;
}
 
源代码12 项目: Aria2App   文件: FileTypeTextView.java
public static float getFitTextSize(@NonNull TextPaint paint, float width, @NonNull String text) {
    float nowWidth = paint.measureText(text);
    return width / nowWidth * paint.getTextSize();
}
 
源代码13 项目: Pocket-Plays-for-Twitch   文件: FontFitTextView.java
/**
 * 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;
}
 
源代码14 项目: android-slidr   文件: Sushi.java
private float calculateTextMultilineHeight(String text, TextPaint textPaint) {
    return text.split("\n").length * textPaint.getTextSize();
}
 
源代码15 项目: Telegram-FOSS   文件: TooManyCommunitiesHintCell.java
public TooManyCommunitiesHintCell(Context context) {
    super(context);

    imageView = new ImageView(context);
    imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chats_nameMessage_threeLines), PorterDuff.Mode.MULTIPLY));

    headerTextView = new TextView(context);
    headerTextView.setTextColor(Theme.getColor(Theme.key_chats_nameMessage_threeLines));
    headerTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
    headerTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    headerTextView.setGravity(Gravity.CENTER);
    addView(headerTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 52, 75, 52, 0));

    messageTextView = new TextView(context);
    messageTextView.setTextColor(Theme.getColor(Theme.key_chats_message));
    messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    messageTextView.setGravity(Gravity.CENTER);
    addView(messageTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 36, 110, 36, 0));

    TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
    textPaint.setColor(Color.WHITE);
    textPaint.setTextSize(AndroidUtilities.dp(12));
    textPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

    String s = "500";
    imageLayout = new FrameLayout(context) {

        RectF rect = new RectF();


        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            paint.setColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText));

            canvas.save();
            canvas.translate(getMeasuredWidth() - textPaint.measureText(s) - AndroidUtilities.dp(8), AndroidUtilities.dpf2(7f));
            rect.set(0, 0, textPaint.measureText(s), textPaint.getTextSize());
            rect.inset(-AndroidUtilities.dp(6), -AndroidUtilities.dp(3));
            float r = (textPaint.getTextSize()) / 2f + AndroidUtilities.dp(3);
            canvas.drawRoundRect(rect, r, r, paint);
            canvas.drawText(s, 0, textPaint.getTextSize() - AndroidUtilities.dpf2(2f), textPaint);
            canvas.restore();
        }
    };
    imageLayout.setWillNotDraw(false);
    imageLayout.addView(imageView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL));
    addView(imageLayout, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 12, 0, 6));
    headerTextView.setText(LocaleController.getString("TooManyCommunities", R.string.TooManyCommunities));
    imageView.setImageResource(R.drawable.groups_limit1);
}
 
源代码16 项目: android-slidr   文件: Slidr.java
private float calculateTextMultilineHeight(String text, TextPaint textPaint) {
    return text.split("\n").length * textPaint.getTextSize();
}
 
/**
 * 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;
    }

    // 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
        StaticLayout layout = new StaticLayout(text, textPaint, 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
    textPaint.setTextSize(targetTextSize);
    setLineSpacing(mSpacingAdd, mSpacingMult);

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

    // Reset force resize flag
    mNeedsResize = false;
}
 
源代码18 项目: Telegram   文件: TooManyCommunitiesHintCell.java
public TooManyCommunitiesHintCell(Context context) {
    super(context);

    imageView = new ImageView(context);
    imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chats_nameMessage_threeLines), PorterDuff.Mode.MULTIPLY));

    headerTextView = new TextView(context);
    headerTextView.setTextColor(Theme.getColor(Theme.key_chats_nameMessage_threeLines));
    headerTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
    headerTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    headerTextView.setGravity(Gravity.CENTER);
    addView(headerTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 52, 75, 52, 0));

    messageTextView = new TextView(context);
    messageTextView.setTextColor(Theme.getColor(Theme.key_chats_message));
    messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    messageTextView.setGravity(Gravity.CENTER);
    addView(messageTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 36, 110, 36, 0));

    TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
    textPaint.setColor(Color.WHITE);
    textPaint.setTextSize(AndroidUtilities.dp(12));
    textPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

    String s = "500";
    imageLayout = new FrameLayout(context) {

        RectF rect = new RectF();


        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            paint.setColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText));

            canvas.save();
            canvas.translate(getMeasuredWidth() - textPaint.measureText(s) - AndroidUtilities.dp(8), AndroidUtilities.dpf2(7f));
            rect.set(0, 0, textPaint.measureText(s), textPaint.getTextSize());
            rect.inset(-AndroidUtilities.dp(6), -AndroidUtilities.dp(3));
            float r = (textPaint.getTextSize()) / 2f + AndroidUtilities.dp(3);
            canvas.drawRoundRect(rect, r, r, paint);
            canvas.drawText(s, 0, textPaint.getTextSize() - AndroidUtilities.dpf2(2f), textPaint);
            canvas.restore();
        }
    };
    imageLayout.setWillNotDraw(false);
    imageLayout.addView(imageView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL));
    addView(imageLayout, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 12, 0, 6));
    headerTextView.setText(LocaleController.getString("TooManyCommunities", R.string.TooManyCommunities));
    imageView.setImageResource(R.drawable.groups_limit1);
}
 
源代码19 项目: Simple-Solitaire   文件: AutoResizingTextView.java
/**
 * 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;
}
 
源代码20 项目: oneHookLibraryAndroid   文件: AutoResizeTextView.java
/**
 * 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;
}