下面列出了android.text.TextPaint#measureText ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void measure(BaseDanmaku danmaku, TextPaint paint, boolean fromWorkerThread) {
if (this.mProxy != null) {
this.mProxy.prepareDrawing(danmaku, fromWorkerThread);
}
float w = 0.0f;
Float textHeight = Float.valueOf(0.0f);
if (danmaku.lines == null) {
if (danmaku.text == null) {
w = 0.0f;
} else {
w = paint.measureText(danmaku.text.toString());
textHeight = getCacheHeight(danmaku, paint);
}
danmaku.paintWidth = w;
danmaku.paintHeight = textHeight.floatValue();
return;
}
textHeight = getCacheHeight(danmaku, paint);
for (String tempStr : danmaku.lines) {
if (tempStr.length() > 0) {
w = Math.max(paint.measureText(tempStr), w);
}
}
danmaku.paintWidth = w;
danmaku.paintHeight = ((float) danmaku.lines.length) * textHeight.floatValue();
}
public void resizeText(int paramInt1, int paramInt2) {
CharSequence localCharSequence = getText();
if ((localCharSequence == null) || (localCharSequence.length() == 0) || (paramInt2 <= 0) || (paramInt1 <= 0))
return;
TextPaint localTextPaint = getPaint();
StaticLayout localStaticLayout = new StaticLayout(localCharSequence, localTextPaint, paramInt1, Layout.Alignment.ALIGN_NORMAL, 1.25F, 0.0F, true);
int i = localStaticLayout.getLineCount();
int j = paramInt2 / (localStaticLayout.getHeight() / i);
if (i > j) {
int k = localStaticLayout.getLineStart(j - 1);
int m = localStaticLayout.getLineEnd(j - 1);
float f1 = localStaticLayout.getLineWidth(j - 1);
float f2 = localTextPaint.measureText(this.mEllipsis);
while (paramInt1 < f1 + f2) {
m--;
f1 = localTextPaint.measureText(localCharSequence.subSequence(k, m + 1).toString());
}
setText(localCharSequence.subSequence(0, m) + this.mEllipsis);
}
setMaxLines(j);
this.mNeedsResize = false;
}
private void initText() {
if (!hasText)
return;
mTextPaint = new TextPaint();
mTextPaint.setAntiAlias(true);
mTextPaint.setTextSize(textSize);
mTextPaint.setColor(textColor);
if (hasTextTypefacePath)
setTypeface(textTypefacePath);
else if (null != textTypeface) {
setTypeface(textTypeface);
}
// default to a single line of text
int width = (int) mTextPaint.measureText(text);
mStaticLayout = new StaticLayout(text, mTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
mStaticLayoutOverlay = new StaticLayout(text, mTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
}
public UEFontAwesomeDrawable(Context context, final View view, String text, int color) {
this.text = Html.fromHtml(text).toString();
mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
mTextPaint.setTypeface(typeface);
mTextPaint.setDither(true);
mTextPaint.setColor(color);
mTextPaint.setTextAlign(Paint.Align.CENTER);
mTextPaint.measureText(text);
view.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
@Override
public boolean onPreDraw() {
width = view.getWidth();
height = view.getHeight();
mTextPaint.setTextSize(Math.min(width, height));
view.getViewTreeObserver().removeOnPreDrawListener(this);
return false;
}
});
}
private CharSequence getTruncatedText(int availWidth) {
final TextPaint paint = getPaint();
// Calculate the width the template takes.
final String emptyTemplate = String.format(mTemplate, "");
final float emptyTemplateWidth = paint.measureText(emptyTemplate);
// Calculate the available width for the content.
final float contentWidth = Math.max(availWidth - emptyTemplateWidth, 0.f);
// Ellipsize the content to the available width.
CharSequence clipped = TextUtils.ellipsize(mContent, paint, contentWidth, TruncateAt.END);
// Build the full string, which should fit within availWidth.
return String.format(mTemplate, clipped);
}
/**
* Recursive binary search to find the best size for the text.
*
* Adapted from https://github.com/grantland/android-autofittextview
*/
public static float getSingleLineTextSize(String text,
TextPaint paint,
float targetWidth,
float low,
float high,
float precision,
DisplayMetrics metrics) {
final float mid = (low + high) / 2.0f;
paint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, mid, metrics));
final float maxLineWidth = paint.measureText(text);
if ((high - low) < precision) {
return low;
} else if (maxLineWidth > targetWidth) {
return getSingleLineTextSize(text, paint, targetWidth, low, mid, precision, metrics);
} else if (maxLineWidth < targetWidth) {
return getSingleLineTextSize(text, paint, targetWidth, mid, high, precision, metrics);
} else {
return mid;
}
}
public int getLineCount(String text, int maxWidth) {
Paint paint = new Paint();
paint.setTextSize(contentTv.getTextSize());
paint.setTypeface(contentTv.getTypeface());
TextPaint mTextPaint = contentTv.getPaint();
mTextPaint.setTextSize(contentTv.getTextSize());
int mTextViewWidth = (int) mTextPaint.measureText(text);
int lineCount = mTextViewWidth / maxWidth;
int ext = mTextViewWidth % maxWidth;
if (ext > 0) lineCount++;
return lineCount;
}
private void resizeTextIfNeeded(CharSequence text) {
if (mWidth <= 0 || TextUtils.isEmpty(text)) {
return;
}
TextPaint paint = getPaint();
float width = paint.measureText(text, 0, text.length());
float size = getTextSize();
while (width > mWidth) {
// It needs to be resized, if possible
if (size > mMinSize) {
// We can still get smaller
size = Math.max(size - mOneSp, mMinSize);
setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
width = paint.measureText(text, 0, text.length());
} else {
// We cannot go any smaller! Give up.
return;
}
}
}
private static float getLetterSpacing(CharSequence text, TextPaint paint, float targetWidth,
float low, float high, float precision) {
float mid = (low + high) / 2.0f;
paint.setLetterSpacing(mid);
float measuredWidth = paint.measureText(text, 0, text.length());
if (high - low < precision) {
if (measuredWidth < targetWidth) {
return mid;
} else {
return low;
}
} else if (measuredWidth > targetWidth) {
return getLetterSpacing(text, paint, targetWidth, low, mid, precision);
} else if (measuredWidth < targetWidth) {
return getLetterSpacing(text, paint, targetWidth, mid, high, precision);
} else {
return mid;
}
}
public static int maxTextSize(String text, int maxWidth) {
TextPaint paint = new TextPaint();
for (int textSize = 10;; ++textSize) {
paint.setTextSize(textSize);
if (paint.measureText(text) > maxWidth) return textSize - 1;
}
}
/**
* Recursive binary search to find the best size for the text.
*
* Adapted from https://github.com/grantland/android-autofittextview
*
* @author Melvin Lobo
*/
public static float getSingleLineTextSize(String text, TextPaint paint, float targetWidth, float low, float high, float precision,
DisplayMetrics metrics) {
/*
* Find the mid
*/
final float mid = (low + high) / 2.0f;
/*
* Get the maximum text width for the Mid
*/
paint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, mid, metrics));
final float maxLineWidth = paint.measureText(text);
/*
* If the value is not close to precision, based on if its greater than or less than the target width,
* we move to either side of the scle divided by the mid and repeat the process again
*/
if ((high - low) < precision) {
return low;
} else if (maxLineWidth > targetWidth) {
return getSingleLineTextSize(text, paint, targetWidth, low, mid, precision, metrics);
} else if (maxLineWidth < targetWidth) {
return getSingleLineTextSize(text, paint, targetWidth, mid, high, precision, metrics);
} else {
return mid;
}
}
private Bitmap genBitmapFromStr(String str, TextPaint textPaint, float density) {
if (TextUtils.isEmpty(str)) {
return null;
}
Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
int h = (int) (Math.abs(fontMetrics.ascent) + Math.abs(fontMetrics.descent));
int w = (int) textPaint.measureText(str);
Bitmap bitmap = PhotoUtil.createBitmapOrNull(w, h, Bitmap.Config.ARGB_4444);
if (bitmap == null) {
return null;
}
Canvas canvas = new Canvas(bitmap);
// 描外层
textPaint.setColor(0xFF343434);
textPaint.setStrokeWidth(density * STROKE_WIDTH_DP + 0.5f); // 描边宽度
textPaint.setStyle(Paint.Style.FILL_AND_STROKE); //描边种类
textPaint.setFakeBoldText(true); // 外层text采用粗体
// textPaint.setShadowLayer(1, 0, 0, 0); //字体的阴影效果,可以忽略
canvas.drawText(str, 0, Math.abs(fontMetrics.ascent), textPaint);
// 描内层,恢复原先的画笔
textPaint.setColor(0xFFFFFFFF);
textPaint.setStrokeWidth(0);
textPaint.setStyle(Paint.Style.FILL_AND_STROKE);
textPaint.setFakeBoldText(false);
// textPaint.setShadowLayer(0, 0, 0, 0);
canvas.drawText(str, 0, Math.abs(fontMetrics.ascent), textPaint);
return bitmap;
}
private void updateContent() {
if(TextUtils.isEmpty(mTips)){
mTips = "";
mSpreadWidth = mWidthClose;
}else{
TextPaint textPaint = getPaint();
mSpreadWidth = textPaint.measureText(mTips)+ SizeUtils.dp2px(30);
}
setText(mTips);
}
private void fitSnappedSingleLine() {
int targetWidth = getWidth() - getPaddingLeft() - getPaddingRight();
if (targetWidth > 0) {
int style = 0;
TextPaint paint = getPaint();
final String text = getText().toString();
MaterialTypeStyle currentStyle = null;
float currentWidth = Float.MAX_VALUE;
while (currentWidth > targetWidth && style < mStyles.length) {
currentStyle = mStyles[style];
paint.setTextSize(currentStyle.size * scaledDensity);
paint.setTypeface(Typeface.create(currentStyle.fontFamily, Typeface.NORMAL));
currentWidth = paint.measureText(text);
style++;
}
setTextSize(TypedValue.COMPLEX_UNIT_SP, currentStyle.size);
setTypeface(Typeface.create(currentStyle.fontFamily, Typeface.NORMAL));
int currentColour = getCurrentTextColor();
setTextColor(Color.argb(currentStyle.opacity,
Color.red(currentColour),
Color.green(currentColour),
Color.blue(currentColour)));
if (style == mStyles.length) {
setEllipsize(TextUtils.TruncateAt.END);
}
mCalculated = true;
}
}
private void measureTabLayoutTextWidth(int position) {
String title = titles.get(position);
TextView titleView = mSlidingTabLayout.getTitleView(position);
TextPaint paint = titleView.getPaint();
float textWidth = paint.measureText(title);
mSlidingTabLayout.setIndicatorWidth(textWidth / 3);
}
/**
* 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;
}
@Override
protected void onDraw(Canvas canvas) {
TextPaint paint = getPaint();
paint.setColor(getCurrentTextColor());
paint.drawableState = getDrawableState();
width = getMeasuredWidth();
Paint.FontMetrics fm = paint.getFontMetrics();
float firstHeight = getTextSize() - (fm.bottom - fm.descent + fm.ascent - fm.top);
int gravity = getGravity();
if ((gravity & 0x1000) == 0) { // 是否垂直居中
firstHeight = firstHeight + (textHeight - firstHeight) / 2;
}
int paddingTop = getPaddingTop();
int paddingLeft = getPaddingLeft();
int paddingRight = getPaddingRight();
width = width - paddingLeft - paddingRight;
for (int i = 0; i < lines.size(); i++) {
float drawY = i * textHeight + firstHeight;
String line = lines.get(i);
// 绘画起始x坐标
float drawSpacingX = paddingLeft;
float gap = (width - paint.measureText(line));
float interval = gap / (line.length() - 1);
// 绘制最后一行
if (tailLines.contains(i)) {
interval = 0;
if (align == Align.ALIGN_CENTER) {
drawSpacingX += gap / 2;
} else if (align == Align.ALIGN_RIGHT) {
drawSpacingX += gap;
}
}
for (int j = 0; j < line.length(); j++) {
float drawX = paint.measureText(line.substring(0, j)) + interval * j;
canvas.drawText(line.substring(j, j + 1), drawX + drawSpacingX, drawY +
paddingTop + textLineSpaceExtra * i, paint);
}
}
}
/**
* 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);
}
public ChartHeaderView(Context context) {
super(context);
TextPaint textPaint = new TextPaint();
textPaint.setTextSize(14);
textPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
textMargin = (int) textPaint.measureText("00 MMM 0000 - 00 MMM 000");
title = new TextView(context);
title.setTextSize(15);
title.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
addView(title, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.START | Gravity.CENTER_VERTICAL, 16, 0, textMargin, 0));
back = new TextView(context);
back.setTextSize(15);
back.setTypeface(Typeface.DEFAULT_BOLD);
back.setGravity(Gravity.START | Gravity.CENTER_VERTICAL);
addView(back, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.START | Gravity.CENTER_VERTICAL, 8, 0, 8, 0));
dates = new TextView(context);
dates.setTextSize(13);
dates.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
dates.setGravity(Gravity.END | Gravity.CENTER_VERTICAL);
addView(dates, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.END | Gravity.CENTER_VERTICAL, 16, 0, 16, 0));
datesTmp = new TextView(context);
datesTmp.setTextSize(13);
datesTmp.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
datesTmp.setGravity(Gravity.END | Gravity.CENTER_VERTICAL);
addView(datesTmp, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.END | Gravity.CENTER_VERTICAL, 16, 0, 16, 0));
datesTmp.setVisibility(View.GONE);
back.setVisibility(View.GONE);
back.setText(LocaleController.getString("ZoomOut", R.string.ZoomOut));
zoomIcon = ContextCompat.getDrawable(getContext(), R.drawable.stats_zoom);
back.setCompoundDrawablesWithIntrinsicBounds(zoomIcon, null, null, null);
back.setCompoundDrawablePadding(AndroidUtilities.dp(4));
back.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(4), AndroidUtilities.dp(8), AndroidUtilities.dp(4));
back.setBackground(Theme.getRoundRectSelectorDrawable(Theme.getColor(Theme.key_featuredStickers_removeButtonText)));
datesTmp.addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
datesTmp.setPivotX(datesTmp.getMeasuredWidth() * 0.7f);
dates.setPivotX(dates.getMeasuredWidth() * 0.7f);
});
recolor();
}
/**
* 测量字符宽度
*
* @param textPaint
* @param text
* @return
*/
public static int getTextWidth(TextPaint textPaint, String text) {
return (int) textPaint.measureText(text);
}