private static Layout createUnrestrictedLayout(@Nonnull TextView view) { CharSequence text = view.getText(); Layout layout = view.getLayout(); TextPaint paint = layout.getPaint(); if (SDK_INT >= M) { return StaticLayout.Builder .obtain(text, 0, text.length(), layout.getPaint(), layout.getWidth()) .setAlignment(layout.getAlignment()) .setLineSpacing(view.getLineSpacingExtra(), view.getLineSpacingMultiplier()) .setIncludePad(view.getIncludeFontPadding()) .setBreakStrategy(view.getBreakStrategy()) .setHyphenationFrequency(view.getHyphenationFrequency()) .build(); } else { return new StaticLayout( text, paint, text.length(), layout.getAlignment(), view.getLineSpacingMultiplier(), view.getLineSpacingExtra(), view.getIncludeFontPadding()); } }
/** * 绘制多行居中文本(方式1) * * @param canvas 画布 */ private void drawCenterMultiText1(Canvas canvas) { String text = "ABC"; // 画笔 TextPaint textPaint = new TextPaint(); textPaint.setAntiAlias(true); textPaint.setColor(Color.GRAY); // 设置宽度超过50dp时换行 StaticLayout staticLayout = new StaticLayout(text, textPaint, dp2px(50), Layout.Alignment.ALIGN_CENTER, 1, 0, false); canvas.save(); // StaticLayout默认从(0,0)点开始绘制 // 如果需要调整位置,只能在绘制之前移动Canvas的起始坐标 canvas.translate(-staticLayout.getWidth() / 2, -staticLayout.getHeight() / 2); staticLayout.draw(canvas); canvas.restore(); }
/** * @return True, if adjustments were made that require the view to be invalidated. */ private boolean adjustBottomLines() { // Bail out if we have a zero width; lines will be adjusted during next layout. if (getWidth() == 0) { return false; } int destBottomLines; textPaint.setTextSize(bottomTextSize); if (tempErrorText != null || helperText != null) { Layout.Alignment alignment = (getGravity() & Gravity.RIGHT) == Gravity.RIGHT || isRTL() ? Layout.Alignment.ALIGN_OPPOSITE : (getGravity() & Gravity.LEFT) == Gravity.LEFT ? Layout.Alignment.ALIGN_NORMAL : Layout.Alignment.ALIGN_CENTER; textLayout = new StaticLayout(tempErrorText != null ? tempErrorText : helperText, textPaint, getWidth() - getBottomTextLeftOffset() - getBottomTextRightOffset() - getPaddingLeft() - getPaddingRight(), alignment, 1.0f, 0.0f, true); destBottomLines = Math.max(textLayout.getLineCount(), minBottomTextLines); } else { destBottomLines = minBottomLines; } if (bottomLines != destBottomLines) { getBottomLinesAnimator(destBottomLines).start(); } bottomLines = destBottomLines; return true; }
private void measure() { TextPaint tp = new TextPaint(); tp.setAntiAlias(true); tp.setColor(mTextColor); tp.setTextSize(mTextSize); strokePaint.setTextSize(mTextSize); // tp.setShadowLayer(4, 0, 0, Color.BLACK); mContentHeight = getFontHeight(tp); staticLayout = new StaticLayout(mContent, tp, (int) Layout.getDesiredWidth(mContent, 0, mContent.length(), tp) + 1, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); mContentWidth = staticLayout.getWidth(); borderStaticLayout = new StaticLayout(mContent, strokePaint, (int) Layout.getDesiredWidth(mContent, 0, mContent.length(), tp) + 1, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); }
private float getDx(final int width, final int horizontalGravity, final Paint paint, final StaticLayout layout) { final boolean centered = paint.getTextAlign() == Paint.Align.CENTER; final float dx; switch (horizontalGravity) { // No support for GravityCompat.END case Gravity.CENTER_HORIZONTAL: dx = (width >> 1) - (centered ? 0 : (layout.getWidth() >> 1) - getPaddingLeft()); break; default: case GravityCompat.START: dx = getPaddingLeft(); break; } return dx; }
private void configureTextLayouts(final int availableWidth) { if (!textLayoutsConfigured) { final int totalNeededPadding = getPaddingLeft() + getPaddingRight(); // Create new static layout only if needed! if ((titleLayout.getWidth() + totalNeededPadding) > availableWidth) { this.titleLayout = new StaticLayout(title, titlePaint, availableWidth, Layout.Alignment.ALIGN_NORMAL, 1.15f, 0, false); } // Create new static layout only if needed! if ((subtitleLayout.getWidth() + totalNeededPadding) > availableWidth) { this.subtitleLayout = new StaticLayout(subtitle, subtitlePaint, availableWidth, Layout.Alignment.ALIGN_NORMAL, 1.15f, 0, false); } textLayoutsConfigured = true; } }
private void updateSecretTimeText() { if (currentMessageObject == null) { return; } String str = currentMessageObject.getSecretTimeString(); if (str == null) { return; } if (currentInfoString == null || !currentInfoString.equals(str)) { currentInfoString = str; infoWidth = (int)Math.ceil(infoPaint.measureText(currentInfoString)); CharSequence str2 = TextUtils.ellipsize(currentInfoString, infoPaint, infoWidth, TextUtils.TruncateAt.END); infoLayout = new StaticLayout(str2, infoPaint, infoWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); invalidate(); } }
public void checkUnreadCounter(int mask) { if (mask != 0 && (mask & MessagesController.UPDATE_MASK_READ_DIALOG_MESSAGE) == 0 && (mask & MessagesController.UPDATE_MASK_NEW_MESSAGE) == 0) { return; } TLRPC.TL_dialog dialog = MessagesController.getInstance().dialogs_dict.get(dialog_id); if (dialog != null && dialog.unread_count != 0) { if (lastUnreadCount != dialog.unread_count) { lastUnreadCount = dialog.unread_count; String countString = String.format("%d", dialog.unread_count); countWidth = Math.max(AndroidUtilities.dp(12), (int) Math.ceil(countPaint.measureText(countString))); countLayout = new StaticLayout(countString, countPaint, countWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false); if (mask != 0) { invalidate(); } } } else if (countLayout != null) { if (mask != 0) { invalidate(); } lastUnreadCount = 0; countLayout = null; } }
public void setTitle(String title) { stringBuilder.setLength(0); if (title != null && title.length() > 0) { stringBuilder.append(title.substring(0, 1)); } if (stringBuilder.length() > 0) { String text = stringBuilder.toString().toUpperCase(); try { textLayout = new StaticLayout(text, namePaint, AndroidUtilities.dp(100), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); if (textLayout.getLineCount() > 0) { textLeft = textLayout.getLineLeft(0); textWidth = textLayout.getLineWidth(0); textHeight = textLayout.getLineBottom(0); } } catch (Exception e) { FileLog.e("tmessages", e); } } else { textLayout = null; } }
private void init() { circlePaint = new Paint(); circlePaint.setAntiAlias(true); circlePaint.setDither(true); circlePaint.setColor(backgroundColor); circlePaint.setStyle(Paint.Style.FILL); textPaint = new TextPaint(); textPaint.setAntiAlias(true); textPaint.setDither(true); textPaint.setColor(textColor); textPaint.setTextSize(textSize); textPaint.setTextAlign(Paint.Align.CENTER); borderPaint = new Paint(); borderPaint.setAntiAlias(true); borderPaint.setDither(true); borderPaint.setColor(borderColor); borderPaint.setStrokeWidth(borderWidth); borderPaint.setStyle(Paint.Style.STROKE); int textWidth = (int) textPaint.measureText(text.substring(0, (text.length() + 1) / 2)); staticLayout = new StaticLayout(text, textPaint, textWidth, Layout.Alignment.ALIGN_NORMAL, 1F, 0, false); }
private void resetting(){ float size; //字体随滑动变化 if (level == 5000) { size = textSize * 1.1f; }else if(level == 10000 || level == 0){ size = textSize * 1f; }else{ float value = (level / 5000f) - 1f; size = textSize + textSize * (1 - Math.abs(value))* 0.1f; } mTextPaint.setTextSize(size); mTextPaint.setColor(defaultTabTextColor); int num = (getMeasuredWidth() - indicatorPadding) / (int) size; // 一行可以放下的字数,默认放置两行文字 // mStaticLayout = new StaticLayout(text, mTextPaint, getMeasuredWidth() - indicatorPadding, Layout.Alignment.ALIGN_NORMAL, 1.0F, 0.0F, false); mStaticLayout = new StaticLayout(text, 0, text.length() > num * 2 ? num * 2 : text.length(), mTextPaint, getMeasuredWidth() - indicatorPadding, Layout.Alignment.ALIGN_NORMAL, 1.0F, 0.0F, false); }
private Layout makeSingleLayout(int i, BoringLayout.Metrics metrics, int i2, Alignment alignment, boolean z, TextUtils.TruncateAt truncateAt, boolean z2) { BoringLayout.Metrics isBoring; if (metrics == UNKNOWN_BORING) { isBoring = BoringLayout.isBoring(this.mText, this.mPaint, this.mBoring); if (isBoring != null) { this.mBoring = isBoring; } } else { isBoring = metrics; } if (isBoring != null) { if (isBoring.width <= i && (truncateAt == null || isBoring.width <= i2)) { return BoringLayout.make(this.mText, this.mPaint, i, alignment, this.mLineSpacingMult, this.mLineSpacingAdd, isBoring, this.mIncludeFontPadding); } else if (z && isBoring.width <= i) { return BoringLayout.make(this.mText, this.mPaint, i, alignment, this.mLineSpacingMult, this.mLineSpacingAdd, isBoring, this.mIncludeFontPadding, truncateAt, i2); } else if (z) { return StaticLayoutWithMaxLines.create(this.mText, 0, this.mText.length(), this.mPaint, i, alignment, this.mLineSpacingMult, this.mLineSpacingAdd, this.mIncludeFontPadding, truncateAt, i2, this.mMaxLines); } else { return new StaticLayout(this.mText, this.mPaint, i, alignment, this.mLineSpacingMult, this.mLineSpacingAdd, this.mIncludeFontPadding); } } else if (z) { return StaticLayoutWithMaxLines.create(this.mText, 0, this.mText.length(), this.mPaint, i, alignment, this.mLineSpacingMult, this.mLineSpacingAdd, this.mIncludeFontPadding, truncateAt, i2, this.mMaxLines); } else { return new StaticLayout(this.mText, this.mPaint, i, alignment, this.mLineSpacingMult, this.mLineSpacingAdd, this.mIncludeFontPadding); } }
/** * Sets the text size of a clone of the view's {@link TextPaint} object * and uses a {@link StaticLayout} instance to measure the height of the text. * * @param source * @param availableWidthPixels * @param textSizePixels * @return the height of the text when placed in a view * with the specified width * and when the text has the specified size. */ private int getTextHeightPixels( CharSequence source, int availableWidthPixels, float textSizePixels) { // Make a copy of the original TextPaint object // since the object gets modified while measuring // (see also the docs for TextView.getPaint() // which states to access it read-only) TextPaint textPaintCopy = new TextPaint(getPaint()); textPaintCopy.setTextSize(textSizePixels); // Measure using a StaticLayout instance StaticLayout staticLayout = new StaticLayout( source, textPaintCopy, availableWidthPixels, Layout.Alignment.ALIGN_NORMAL, mLineSpacingMultiplier, mLineSpacingExtra, true); return staticLayout.getHeight(); }
/** * 绘制文字 * * @param canvas 画布 */ private void drawText(Canvas canvas, String textString) { textRect.left = getPaddingLeft(); textRect.top = getPaddingTop(); textRect.right = getWidth() - getPaddingRight(); textRect.bottom = getHeight() - getPaddingBottom(); TextPaint textPaint = new TextPaint(); // textPaint.setARGB(0xFF, 0xFF, 0, 0); textPaint.setTextSize(50.0F); textPaint.setAntiAlias(true); /** * aboutTheGame :要 绘制 的 字符串 ,textPaint(TextPaint 类型)设置了字符串格式及属性 的画笔,getWidth()为设置 画多宽后 换行,后面的参数是对齐方式... */ StaticLayout layout = new StaticLayout(textString,textPaint,getWidth(), Layout.Alignment.ALIGN_NORMAL,1.0F,0.0F,true); canvas.save(); canvas.translate(10,10); layout.draw(canvas); canvas.restore();//别忘了restore }
public void checkUnreadCounter(int mask) { if (mask != 0 && (mask & MessagesController.UPDATE_MASK_READ_DIALOG_MESSAGE) == 0 && (mask & MessagesController.UPDATE_MASK_NEW_MESSAGE) == 0) { return; } TLRPC.TL_dialog dialog = MessagesController.getInstance().dialogs_dict.get(dialog_id); if (dialog != null && dialog.unread_count != 0) { if (lastUnreadCount != dialog.unread_count) { lastUnreadCount = dialog.unread_count; String countString = String.format("%d", dialog.unread_count); countWidth = Math.max(AndroidUtilities.dp(7), (int) Math.ceil(countPaint.measureText(countString))); countLayout = new StaticLayout(countString, countPaint, countWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false); if (mask != 0) { invalidate(); } } } else if (countLayout != null) { if (mask != 0) { invalidate(); } lastUnreadCount = 0; countLayout = null; } }
public static void drawMultilineText(Canvas c, String text, float x, float y, TextPaint paint, FSize constrainedToSize, MPPointF anchor, float angleDegrees) { StaticLayout textLayout = new StaticLayout( text, 0, text.length(), paint, (int) Math.max(Math.ceil(constrainedToSize.width), 1.f), Layout.Alignment.ALIGN_NORMAL, 1.f, 0.f, false); drawMultilineText(c, textLayout, x, y, paint, anchor, angleDegrees); }
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(); }
public ImageTextStateDisplay(Context c, @NonNull Bitmap bitmap, @NonNull String title, @Nullable String subtitle) { DisplayMetrics dm = c.getResources().getDisplayMetrics(); this.sixteenDp = (int)(16f * dm.density); // Setup default sizes setPadding(sixteenDp, sixteenDp, sixteenDp, sixteenDp); this.titleSpacing = (int)(4f * dm.scaledDensity); this.textImageSpacing = sixteenDp; // Setup title defaults this.titlePaint.setTextAlign(Paint.Align.CENTER); this.titlePaint.setTextSize(18f * dm.scaledDensity); this.titlePaint.setColor(Color.BLACK); this.title = title; // Default to a single line of text this.titleLayout = new StaticLayout(title, titlePaint, (int)titlePaint.measureText(title), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false); // Setup subtitle defaults this.subtitlePaint.setTextSize(14f * dm.scaledDensity); this.subtitlePaint.setTextAlign(Paint.Align.CENTER); this.subtitlePaint.setColor(Color.GRAY); this.subtitle = (subtitle == null ? "Dank yo hommie future is a rapper sdlkfjsldjfslkdjfsldjfasdjfasljdfasjdflasjdflsajd" : subtitle); // Default to a single line of text this.subtitleLayout = new StaticLayout(this.subtitle, subtitlePaint, (int)subtitlePaint.measureText(this.subtitle), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false); this.image = bitmap; }
private void configure(final int availableWidth) { if (!configured) { final int totalNeededPadding = getPaddingLeft() + getPaddingRight(); // Create new static layout only if needed! if ((titleLayout.getWidth() + totalNeededPadding) > availableWidth) { this.titleLayout = new StaticLayout(title, titlePaint, availableWidth, Layout.Alignment.ALIGN_NORMAL, 1.15f, 0, false); } // Create new static layout only if needed! if ((subtitleLayout.getWidth() + totalNeededPadding) > availableWidth) { this.subtitleLayout = new StaticLayout(subtitle, subtitlePaint, availableWidth, Layout.Alignment.ALIGN_NORMAL, 1.15f, 0, false); } final int newImageSize = ((availableWidth + getPaddingLeft() + getPaddingRight()) / 3); this.image = Bitmap.createScaledBitmap(image, newImageSize, newImageSize, false); configured = true; } }
public TextStateDisplay(Context c, @NonNull String title, @Nullable String subtitle) { DisplayMetrics dm = c.getResources().getDisplayMetrics(); // Setup default sizes final int large = (int)(16f * dm.density); setPadding(large, large, large, large); this.titleSpacing = (int)(4f * dm.scaledDensity); // Setup title defaults this.titlePaint.setTextAlign(Paint.Align.CENTER); this.titlePaint.setTextSize(18f * dm.scaledDensity); this.titlePaint.setColor(Color.BLACK); this.title = title; // Default to a single line of text this.titleLayout = new StaticLayout(title, titlePaint, (int)titlePaint.measureText(title), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false); // Setup subtitle defaults this.subtitlePaint.setTextSize(14f * dm.scaledDensity); this.subtitlePaint.setTextAlign(Paint.Align.CENTER); this.subtitlePaint.setColor(Color.GRAY); this.subtitle = subtitle; // Default to a single line of text this.subtitleLayout = new StaticLayout(subtitle, subtitlePaint, (int)subtitlePaint.measureText(subtitle), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false); }
private static int getLineCount(CharSequence text, TextPaint paint, float size, float width, DisplayMetrics displayMetrics) { paint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, size, displayMetrics)); StaticLayout layout = new StaticLayout(text, paint, (int)width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, true); return layout.getLineCount(); }
private void addText() { mTextPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mTextSize, getResources().getDisplayMetrics())); if (!"roboto.ttf".equals(mTypeface)) { mTextPaint.setTypeface(Typeface.createFromAsset(mContext.getAssets(), mTypeface)); mTextStrokePaint.setTypeface(Typeface.createFromAsset(mContext.getAssets(), mTypeface)); } mTextPaint.setFakeBoldText(true); mTextPaint.setAntiAlias(true); mTextPaint.setShadowLayer(mShadowRadius, mShadowDisX, mShadowDisY, mShadowColor); mTextStrokePaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mTextSize, getResources().getDisplayMetrics())); mTextStrokePaint.setStrokeWidth(mStrokeWidth); mTextStrokePaint.setStyle(Paint.Style.STROKE); mTextStrokePaint.setFakeBoldText(true); mTextStrokePaint.setAntiAlias(true); if (mTextGravity == WidgetTextBean.GRAVITY_CENTER || mTextGravity == WidgetTextBean.GRAVITY_HORIZONTAL_CENTER) { mAlignment = StaticLayout.Alignment.ALIGN_CENTER; } else { mAlignment = StaticLayout.Alignment.ALIGN_NORMAL; } mLayout = new StaticLayout(applyLetterSpacing(mText), mTextPaint, mTextRect.width(), mAlignment, 0.9f, mLineSpace, false); mStrokeLayout = new StaticLayout(applyLetterSpacing(mText), mTextStrokePaint, mTextRect.width(), mAlignment, 0.9f, mLineSpace, false); // mTextWidth = mTextPaint.measureText(mText);; mTextWidth = mLayout.getWidth(); mTextHeight = mStrokeLayout.getHeight() >= mLayout.getHeight() ? mStrokeLayout.getHeight() : mLayout.getHeight(); initColor(); }
public void setText(String text) { if (text == null || text.length() == 0) { setVisibility(GONE); return; } if (text != null && oldText != null && text.equals(oldText)) { return; } oldText = text; setVisibility(VISIBLE); if (AndroidUtilities.isTablet()) { width = (int) (AndroidUtilities.getMinTabletSide() * 0.7f); } else { width = (int) (Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) * 0.7f); } SpannableStringBuilder stringBuilder = new SpannableStringBuilder(); String help = LocaleController.getString("BotInfoTitle", R.string.BotInfoTitle); stringBuilder.append(help); stringBuilder.append("\n\n"); stringBuilder.append(text); MessageObject.addLinks(stringBuilder); stringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), 0, help.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); Emoji.replaceEmoji(stringBuilder, textPaint.getFontMetricsInt(), AndroidUtilities.dp(20), false); try { textLayout = new StaticLayout(stringBuilder, textPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); width = 0; height = textLayout.getHeight() + AndroidUtilities.dp(4 + 18); int count = textLayout.getLineCount(); for (int a = 0; a < count; a++) { width = (int) Math.ceil(Math.max(width, textLayout.getLineWidth(a) + textLayout.getLineLeft(a))); } } catch (Exception e) { FileLog.e("tmessage", e); } width += AndroidUtilities.dp(4 + 18); }
private void updateSecretTimeText(MessageObject messageObject) { if (messageObject == null || messageObject.isOut()) { return; } String str = messageObject.getSecretTimeString(); if (str == null) { return; } infoWidth = (int) Math.ceil(infoPaint.measureText(str)); CharSequence str2 = TextUtils.ellipsize(str, infoPaint, infoWidth, TextUtils.TruncateAt.END); infoLayout = new StaticLayout(str2, infoPaint, infoWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); invalidate(); }
private void createLayout(int width) { if (text != null) { try { CharSequence string = TextUtils.ellipsize(text, textPaint, width, TextUtils.TruncateAt.END); layout = new StaticLayout(string, 0, string.length(), textPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); /*if (metrics == null) { metrics = BoringLayout.isBoring(text, textPaint); } if (layout == null) { layout = BoringLayout.make(text, textPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, metrics, false, TextUtils.TruncateAt.END, width); } else { layout = ((BoringLayout) layout).replaceOrMake(text, textPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, metrics, false, TextUtils.TruncateAt.END, width); }*/ /*if (spannableStringBuilder == null) { spannableStringBuilder = new SpannableStringBuilder(text); layout = new DynamicLayout(text, text, textPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false, TextUtils.TruncateAt.END, width); } else { spannableStringBuilder.replace(0, text.length(), text); }*/ if (layout.getLineCount() > 0) { if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT) { offsetX = -(int) layout.getLineLeft(0); } else if (layout.getLineLeft(0) == 0) { offsetX = (int) (width - layout.getLineWidth(0)); } else { offsetX = 0; } } } catch (Exception e) { //ignore } } }
private int prepareBottomPadding() { int targetNbLines = minNbErrorLines; if (error != null) { staticLayout = new StaticLayout(error, textPaint, getWidth() - getPaddingRight() - getPaddingLeft(), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, true); int nbErrorLines = staticLayout.getLineCount(); targetNbLines = Math.max(minNbErrorLines, nbErrorLines); } return targetNbLines; }
private int getTextHeight(CharSequence source, TextPaint paint, int width, float textSize) { // modified: make a copy of the original TextPaint object for measuring // (apparently the object gets modified while measuring, see also the // docs for TextView.getPaint() (which states to access it read-only) TextPaint paintCopy = new TextPaint(paint); // Update the text paint object paintCopy.setTextSize(textSize); // Measure using a static layout StaticLayout layout = new StaticLayout(source, paintCopy, width, Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, true); return layout.getHeight(); }
/** * 重绘文字,两端对齐 * * @param canvas */ private void drawTextWithJustify(Canvas canvas) { // 文字画笔 TextPaint textPaint = getPaint(); textPaint.setColor(getCurrentTextColor()); textPaint.drawableState = getDrawableState(); String text_str = getText().toString(); // 当前所在行的Y向偏移 int currentLineOffsetY = getPaddingTop(); currentLineOffsetY += getTextSize(); Layout layout = getLayout(); //循环每一行,绘制文字 for (int i = 0; i < layout.getLineCount(); i++) { int lineStart = layout.getLineStart(i); int lineEnd = layout.getLineEnd(i); //获取到TextView每行中的内容 String line_str = text_str.substring(lineStart, lineEnd); // 获取每行字符串的宽度(不包括字符间距) float desiredWidth = StaticLayout.getDesiredWidth(text_str, lineStart, lineEnd, getPaint()); if (isLineNeedJustify(line_str)) { //最后一行不需要重绘 if (i == layout.getLineCount() - 1) { canvas.drawText(line_str, getPaddingLeft(), currentLineOffsetY, textPaint); } else { drawJustifyTextForLine(canvas, line_str, desiredWidth, currentLineOffsetY); } } else { canvas.drawText(line_str, getPaddingLeft(), currentLineOffsetY, textPaint); } //更新行Y向偏移 currentLineOffsetY += getLineHeight(); } }
public void setAyahString(@NonNull String suraAyah) { if (!suraAyah.equals(this.suraAyah)) { this.suraAyah = suraAyah; this.textLayout = new StaticLayout(suraAyah, textPaint, boxWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false); invalidate(); } }