Java Code Examples for android.text.StaticLayout#getLineCount()
The following examples show how to use
android.text.StaticLayout#getLineCount() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LetterDrawable.java From TelePlus-Android with GNU General Public License v2.0 | 6 votes |
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(e); } } else { textLayout = null; } }
Example 2
Source File: FlowTextHelperImpl.java From Overchan-Android with GNU General Public License v3.0 | 6 votes |
public static boolean flowText(SpannableStringBuilder ss, int width, int height, int textFullWidth, TextPaint textPaint) { StaticLayout l = new StaticLayout(ss, 0, ss.length(), textPaint, textFullWidth - width, Layout.Alignment.ALIGN_NORMAL, 1.0F, 0, false); int lines = 0; while (lines < l.getLineCount() && l.getLineBottom(lines) < height) ++lines; ++lines; int endPos; if (lines < l.getLineCount()) { endPos = l.getLineStart(lines); } else { return false; } if (ss.charAt(endPos-1) != '\n' && ss.charAt(endPos-1) != '\r') { if (ss.charAt(endPos-1) == ' ') { ss.replace(endPos-1, endPos, "\n"); } else { ss.insert(endPos, "\n"); } } ss.setSpan(new FloatingMarginSpan(lines, width), 0, endPos, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return true; }
Example 3
Source File: LyricView.java From MusicPlayer_XiangDa with GNU General Public License v3.0 | 6 votes |
public void setLyricFile(File file, String charsetName) { if (file != null && file.exists()) { try { setupLyricResource(new FileInputStream(file), charsetName); for (int i = 0; i < mLyricInfo.songLines.size(); i++) { StaticLayout staticLayout = new StaticLayout(mLyricInfo.songLines.get(i).content, mTextPaint, (int) getRawSize(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_MAX_LENGTH), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); if (staticLayout.getLineCount() > 1) { mEnableLineFeed = true; mExtraHeight = mExtraHeight + (staticLayout.getLineCount() - 1) * mTextHeight; } mLineFeedRecord.add(i, mExtraHeight); } } catch (FileNotFoundException e) { e.printStackTrace(); } } else { invalidateView(); } }
Example 4
Source File: AutofitTextView.java From UltimateAndroid with Apache License 2.0 | 5 votes |
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(); }
Example 5
Source File: AutofitHelper.java From stynico with MIT License | 5 votes |
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(); }
Example 6
Source File: WebPlayerView.java From TelePlus-Android with GNU General Public License v2.0 | 5 votes |
public void setDuration(int value) { if (duration == value || value < 0 || isStream) { return; } duration = value; durationLayout = new StaticLayout(String.format(Locale.US, "%d:%02d", duration / 60, duration % 60), textPaint, AndroidUtilities.dp(1000), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); if (durationLayout.getLineCount() > 0) { durationWidth = (int) Math.ceil(durationLayout.getLineWidth(0)); } invalidate(); }
Example 7
Source File: AutofitHelper.java From DarkCalculator with MIT License | 5 votes |
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(); }
Example 8
Source File: LinkPath.java From Telegram-FOSS with GNU General Public License v2.0 | 5 votes |
public void setCurrentLayout(StaticLayout layout, int start, float yOffset) { currentLayout = layout; currentLine = layout.getLineForOffset(start); lastTop = -1; heightOffset = yOffset; if (Build.VERSION.SDK_INT >= 28) { int lineCount = layout.getLineCount(); if (lineCount > 0) { lineHeight = layout.getLineBottom(lineCount - 1) - layout.getLineTop(lineCount - 1); } } }
Example 9
Source File: BannerTextView.java From SmartChart with Apache License 2.0 | 5 votes |
private int getHeightS() { TextPaint textPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG); textPaint.setTextSize(getTextSize()); StaticLayout staticLayout = new StaticLayout(textList.get(currentPosition), textPaint, getWidth() - getPaddingLeft() - getPaddingRight(), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false); int height = staticLayout.getHeight(); if (staticLayout.getLineCount() > getMaxLines()) { int lineCount = staticLayout.getLineCount(); height = staticLayout.getLineBottom(getMaxLines() - 1); } return height; }
Example 10
Source File: AutofitTextView.java From UltimateAndroid with Apache License 2.0 | 5 votes |
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(); }
Example 11
Source File: StaticLayoutHelper.java From TextLayoutBuilder with Apache License 2.0 | 5 votes |
/** * Attempts to fix a StaticLayout with wrong layout information that can result in * StringIndexOutOfBoundsException during layout.draw(). * * @param layout The {@link StaticLayout} to fix * @return Whether the layout was fixed or not */ public static boolean fixLayout(StaticLayout layout) { int lineStart = layout.getLineStart(0); for (int i = 0, lineCount = layout.getLineCount(); i < lineCount; ++i) { int lineEnd = layout.getLineEnd(i); if (lineEnd < lineStart) { // Bug, need to swap lineStart and lineEnd try { Field mLinesField = StaticLayout.class.getDeclaredField("mLines"); mLinesField.setAccessible(true); Field mColumnsField = StaticLayout.class.getDeclaredField("mColumns"); mColumnsField.setAccessible(true); int[] mLines = (int[]) mLinesField.get(layout); int mColumns = mColumnsField.getInt(layout); // swap lineStart and lineEnd by swapping all the following data: // mLines[mColumns * i.. mColumns * i+1] <-> mLines[mColumns * (i+1)..mColumns * (i+2)] for (int j = 0; j < mColumns; ++j) { swap(mLines, mColumns * i + j, mColumns * i + j + mColumns); } } catch (Exception e) { // something is wrong, bail out break; } // start over return false; } lineStart = lineEnd; } return true; }
Example 12
Source File: SharedLinkCell.java From Telegram with GNU General Public License v2.0 | 4 votes |
@Override protected void onDraw(Canvas canvas) { if (titleLayout != null) { canvas.save(); canvas.translate(AndroidUtilities.dp(LocaleController.isRTL ? 8 : AndroidUtilities.leftBaseline), titleY); titleLayout.draw(canvas); canvas.restore(); } if (descriptionLayout != null) { descriptionTextPaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); canvas.save(); canvas.translate(AndroidUtilities.dp(LocaleController.isRTL ? 8 : AndroidUtilities.leftBaseline), descriptionY); descriptionLayout.draw(canvas); canvas.restore(); } if (descriptionLayout2 != null) { descriptionTextPaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); canvas.save(); canvas.translate(AndroidUtilities.dp(LocaleController.isRTL ? 8 : AndroidUtilities.leftBaseline), description2Y); descriptionLayout2.draw(canvas); canvas.restore(); } if (!linkLayout.isEmpty()) { descriptionTextPaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhiteLinkText)); int offset = 0; for (int a = 0; a < linkLayout.size(); a++) { StaticLayout layout = linkLayout.get(a); if (layout.getLineCount() > 0) { canvas.save(); canvas.translate(AndroidUtilities.dp(LocaleController.isRTL ? 8 : AndroidUtilities.leftBaseline), linkY + offset); if (pressedLink == a) { canvas.drawPath(urlPath, Theme.linkSelectionPaint); } layout.draw(canvas); canvas.restore(); offset += layout.getLineBottom(layout.getLineCount() - 1); } } } letterDrawable.draw(canvas); if (drawLinkImageView) { linkImageView.draw(canvas); } if (needDivider) { if (LocaleController.isRTL) { canvas.drawLine(0, getMeasuredHeight() - 1, getMeasuredWidth() - AndroidUtilities.dp(AndroidUtilities.leftBaseline), getMeasuredHeight() - 1, Theme.dividerPaint); } else { canvas.drawLine(AndroidUtilities.dp(AndroidUtilities.leftBaseline), getMeasuredHeight() - 1, getMeasuredWidth(), getMeasuredHeight() - 1, Theme.dividerPaint); } } }
Example 13
Source File: AutoResizeTextView.java From oneHookLibraryAndroid with Apache License 2.0 | 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 14
Source File: FontFitTextView.java From Pocket-Plays-for-Twitch with GNU General Public License v3.0 | 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 15
Source File: GroupCreateSpan.java From TelePlus-Android with GNU General Public License v2.0 | 4 votes |
public GroupCreateSpan(Context context, TLRPC.User user, ContactsController.Contact contact) { super(context); currentContact = contact; deleteDrawable = getResources().getDrawable(R.drawable.delete); textPaint.setTextSize(AndroidUtilities.dp(14)); avatarDrawable = new AvatarDrawable(); avatarDrawable.setTextSize(AndroidUtilities.dp(12)); if (user != null) { avatarDrawable.setInfo(user); uid = user.id; } else { avatarDrawable.setInfo(0, contact.first_name, contact.last_name, false); uid = contact.contact_id; key = contact.key; } imageReceiver = new ImageReceiver(); imageReceiver.setRoundRadius(AndroidUtilities.dp(16)); imageReceiver.setParentView(this); imageReceiver.setImageCoords(0, 0, AndroidUtilities.dp(32), AndroidUtilities.dp(32)); int maxNameWidth; if (AndroidUtilities.isTablet()) { maxNameWidth = AndroidUtilities.dp(530 - 32 - 18 - 57 * 2) / 2; } else { maxNameWidth = (Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) - AndroidUtilities.dp(32 + 18 + 57 * 2)) / 2; } String firstName; if (user != null) { firstName = UserObject.getFirstName(user); } else { if (!TextUtils.isEmpty(contact.first_name)) { firstName = contact.first_name; } else { firstName = contact.last_name; } } CharSequence name = TextUtils.ellipsize(firstName.replace('\n', ' '), textPaint, maxNameWidth, TextUtils.TruncateAt.END); nameLayout = new StaticLayout(name, textPaint, 1000, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); if (nameLayout.getLineCount() > 0) { textWidth = (int) Math.ceil(nameLayout.getLineWidth(0)); textX = -nameLayout.getLineLeft(0); } TLRPC.FileLocation photo = null; if (user != null && user.photo != null) { photo = user.photo.photo_small; } imageReceiver.setImage(photo, null, "50_50", avatarDrawable, null, null, 0, null, 1); updateColors(); }
Example 16
Source File: Utils.java From Ticket-Analysis with MIT License | 4 votes |
public static void drawMultilineText(Canvas c, StaticLayout textLayout, float x, float y, TextPaint paint, MPPointF anchor, float angleDegrees) { float drawOffsetX = 0.f; float drawOffsetY = 0.f; float drawWidth; float drawHeight; final float lineHeight = paint.getFontMetrics(mFontMetricsBuffer); drawWidth = textLayout.getWidth(); drawHeight = textLayout.getLineCount() * lineHeight; // Android sometimes has pre-padding drawOffsetX -= mDrawTextRectBuffer.left; // Android does not snap the bounds to line boundaries, // and draws from bottom to top. // And we want to normalize it. drawOffsetY += drawHeight; // To have a consistent point of reference, we always draw left-aligned Paint.Align originalTextAlign = paint.getTextAlign(); paint.setTextAlign(Paint.Align.LEFT); if (angleDegrees != 0.f) { // Move the text drawing rect in a way that it always rotates around its center drawOffsetX -= drawWidth * 0.5f; drawOffsetY -= drawHeight * 0.5f; float translateX = x; float translateY = y; // Move the "outer" rect relative to the anchor, assuming its centered if (anchor.x != 0.5f || anchor.y != 0.5f) { final FSize rotatedSize = getSizeOfRotatedRectangleByDegrees( drawWidth, drawHeight, angleDegrees); translateX -= rotatedSize.width * (anchor.x - 0.5f); translateY -= rotatedSize.height * (anchor.y - 0.5f); FSize.recycleInstance(rotatedSize); } c.save(); c.translate(translateX, translateY); c.rotate(angleDegrees); c.translate(drawOffsetX, drawOffsetY); textLayout.draw(c); c.restore(); } else { if (anchor.x != 0.f || anchor.y != 0.f) { drawOffsetX -= drawWidth * anchor.x; drawOffsetY -= drawHeight * anchor.y; } drawOffsetX += x; drawOffsetY += y; c.save(); c.translate(drawOffsetX, drawOffsetY); textLayout.draw(c); c.restore(); } paint.setTextAlign(originalTextAlign); }
Example 17
Source File: ChatBaseCell.java From Yahala-Messenger with MIT License | 4 votes |
public void setMessageObject(MessageObject messageObject) { currentMessageObject = messageObject; isPressed = false; isCheckPressed = true; isAvatarVisible = false; wasLayout = false; /* if (currentMessageObject.messageOwner.getId() < 0 && currentMessageObject.messageOwner.getSend_state() != MessagesController.MESSAGE_SEND_STATE_SEND_ERROR && currentMessageObject.messageOwner.getSend_state() != MessagesController.MESSAGE_SEND_STATE_SENT) { if (MessagesController.getInstance().sendingMessages.get(currentMessageObject.messageOwner.getId()) == null) { currentMessageObject.messageOwner.setSend_state(MessagesController.MESSAGE_SEND_STATE_SEND_ERROR); } }*/ //FileLog.e("messageObject.messageOwner.getJid()",messageObject.messageOwner.getJid()+""); try { currentUser = ContactsController.getInstance().friendsDict.get(messageObject.messageOwner.getJid()); if (isChat && currentMessageObject.isOut()) { isAvatarVisible = true; if (currentUser != null) { if (currentUser.photo != null) { currentPhoto = currentUser.photo.photo_small; } else { currentPhoto = null; } avatarImage.setImage(currentPhoto, "50_50", getResources().getDrawable(Utilities.getUserAvatarForId(currentUser.id))); } else { avatarImage.setImage((TLRPC.FileLocation) null, "50_50", null); } } if (!media) { if (currentMessageObject.isOut()) { currentTimePaint = timePaintOut; } else { currentTimePaint = timePaintIn; } } else { currentTimePaint = timeMediaPaint; } currentTimeString = LocaleController.formatterDay.format(currentMessageObject.messageOwner.getDate()); timeWidth = (int) Math.ceil(currentTimePaint.measureText(currentTimeString)); namesOffset = 0; if (drawName && isChat && currentUser != null && currentMessageObject.messageOwner.getOut() != 1) { currentNameString = Utilities.formatName(currentUser.first_name, currentUser.last_name); nameWidth = getMaxNameWidth(); CharSequence nameStringFinal = TextUtils.ellipsize(currentNameString.replace("\n", " "), namePaint, nameWidth - OSUtilities.dp(12), TextUtils.TruncateAt.END); nameLayout = new StaticLayout(nameStringFinal, namePaint, nameWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); if (nameLayout.getLineCount() > 0) { nameWidth = (int) Math.ceil(nameLayout.getLineWidth(0)); namesOffset += OSUtilities.dp(18); nameOffsetX = nameLayout.getLineLeft(0); } else { nameWidth = 0; } } else { currentNameString = null; nameLayout = null; nameWidth = 0; } // if (drawForwardedName && messageObject.messageOwner.tl_message instanceof TLRPC.TL_messageForwarded) { /* currentForwardUser = MessagesController.getInstance().users.get(messageObject.messageOwner.fwd_from_id); if (currentForwardUser != null) { currentForwardNameString = Utilities.formatName(currentForwardUser.first_name, currentForwardUser.last_name); forwardedNameWidth = getMaxNameWidth(); CharSequence str = TextUtils.ellipsize(currentForwardNameString.replace("\n", " "), forwardNamePaint, forwardedNameWidth - AndroidUtilities.dp(40), TextUtils.TruncateAt.END); str = Html.fromHtml(String.format("%s<br>%s <b>%s</b>", LocaleController.getString("ForwardedMessage", R.string.ForwardedMessage), LocaleController.getString("From", R.string.From), str)); forwardedNameLayout = new StaticLayout(str, forwardNamePaint, forwardedNameWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); if (forwardedNameLayout.getLineCount() > 1) { forwardedNameWidth = Math.max((int) Math.ceil(forwardedNameLayout.getLineWidth(0)), (int) Math.ceil(forwardedNameLayout.getLineWidth(1))); namesOffset += AndroidUtilities.dp(36); forwardNameOffsetX = Math.min(forwardedNameLayout.getLineLeft(0), forwardedNameLayout.getLineLeft(1)); } else { forwardedNameWidth = 0; } } else { currentForwardNameString = null; forwardedNameLayout = null; forwardedNameWidth = 0; }*/ // } else { currentForwardNameString = null; forwardedNameLayout = null; forwardedNameWidth = 0; // } requestLayout(); } catch (Exception e) { } }
Example 18
Source File: BitmapUtils.java From AndroidWM with Apache License 2.0 | 4 votes |
/** * build a bitmap from a text. * * @return {@link Bitmap} the bitmap return. */ public static Bitmap textAsBitmap(Context context, WatermarkText watermarkText) { TextPaint watermarkPaint = new TextPaint(); watermarkPaint.setColor(watermarkText.getTextColor()); watermarkPaint.setStyle(watermarkText.getTextStyle()); if (watermarkText.getTextAlpha() >= 0 && watermarkText.getTextAlpha() <= 255) { watermarkPaint.setAlpha(watermarkText.getTextAlpha()); } float value = (float) watermarkText.getTextSize(); int pixel = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, context.getResources().getDisplayMetrics()); watermarkPaint.setTextSize(pixel); if (watermarkText.getTextShadowBlurRadius() != 0 || watermarkText.getTextShadowXOffset() != 0 || watermarkText.getTextShadowYOffset() != 0) { watermarkPaint.setShadowLayer(watermarkText.getTextShadowBlurRadius(), watermarkText.getTextShadowXOffset(), watermarkText.getTextShadowYOffset(), watermarkText.getTextShadowColor()); } if (watermarkText.getTextFont() != 0) { Typeface typeface = ResourcesCompat.getFont(context, watermarkText.getTextFont()); watermarkPaint.setTypeface(typeface); } watermarkPaint.setAntiAlias(true); watermarkPaint.setTextAlign(Paint.Align.LEFT); watermarkPaint.setStrokeWidth(5); float baseline = (int) (-watermarkPaint.ascent() + 1f); Rect bounds = new Rect(); watermarkPaint.getTextBounds(watermarkText.getText(), 0, watermarkText.getText().length(), bounds); int boundWidth = bounds.width() + 20; int mTextMaxWidth = (int) watermarkPaint.measureText(watermarkText.getText()); if (boundWidth > mTextMaxWidth) { boundWidth = mTextMaxWidth; } StaticLayout staticLayout = new StaticLayout(watermarkText.getText(), 0, watermarkText.getText().length(), watermarkPaint, mTextMaxWidth, android.text.Layout.Alignment.ALIGN_NORMAL, 2.0f, 2.0f, false); int lineCount = staticLayout.getLineCount(); int height = (int) (baseline + watermarkPaint.descent() + 3) * lineCount; Bitmap image = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); if (boundWidth > 0 && height > 0) { image = Bitmap.createBitmap(boundWidth, height, Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(image); canvas.drawColor(watermarkText.getBackgroundColor()); staticLayout.draw(canvas); return image; }
Example 19
Source File: AutoResizeTextView.java From watchlist with Apache License 2.0 | 4 votes |
/** * Resizes this view's text size with respect to its width and height * (minus padding). */ private void resizeText() { final int availableHeightPixels = getHeight() - getCompoundPaddingBottom() - getCompoundPaddingTop(); final int availableWidthPixels = getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight(); final CharSequence text = getText(); // Safety check // (Do not resize if the view does not have dimensions or if there is no text) if (text == null || text.length() <= 0 || availableHeightPixels <= 0 || availableWidthPixels <= 0 || mMaxTextSizePixels <= 0) { return; } float targetTextSizePixels = mMaxTextSizePixels; int targetTextHeightPixels = getTextHeightPixels(text, availableWidthPixels, targetTextSizePixels); // Until we either fit within our TextView // or we have reached our minimum text size, // incrementally try smaller sizes while (targetTextHeightPixels > availableHeightPixels && targetTextSizePixels > mMinTextSizePixels) { targetTextSizePixels = Math.max( targetTextSizePixels - 2, mMinTextSizePixels); targetTextHeightPixels = getTextHeightPixels( text, availableWidthPixels, targetTextSizePixels); } // If we have reached our minimum text size and the text still doesn't fit, // append an ellipsis // (NOTE: Auto-ellipsize doesn't work hence why we have to do it here) // depending on the value of getEllipsize()) if (getEllipsize() != null && targetTextSizePixels == mMinTextSizePixels && targetTextHeightPixels > availableHeightPixels) { // Make a copy of the original TextPaint object for measuring TextPaint textPaintCopy = new TextPaint(getPaint()); textPaintCopy.setTextSize(targetTextSizePixels); // Measure using a StaticLayout instance StaticLayout staticLayout = new StaticLayout( text, textPaintCopy, availableWidthPixels, Layout.Alignment.ALIGN_NORMAL, mLineSpacingMultiplier, mLineSpacingExtra, false); // Check that we have a least one line of rendered text if (staticLayout.getLineCount() > 0) { // Since the line at the specific vertical position would be cut off, // we must trim up to the previous line and add an ellipsis int lastLine = staticLayout.getLineForVertical(availableHeightPixels) - 1; if (lastLine >= 0) { int startOffset = staticLayout.getLineStart(lastLine); int endOffset = staticLayout.getLineEnd(lastLine); float lineWidthPixels = staticLayout.getLineWidth(lastLine); float ellipseWidth = textPaintCopy.measureText(mEllipsis); // Trim characters off until we have enough room to draw the ellipsis while (availableWidthPixels < lineWidthPixels + ellipseWidth) { endOffset--; lineWidthPixels = textPaintCopy.measureText( text.subSequence(startOffset, endOffset + 1).toString()); } setText(text.subSequence(0, endOffset) + mEllipsis); } } } super.setTextSize(TypedValue.COMPLEX_UNIT_PX, targetTextSizePixels); // Some devices try to auto adjust line spacing, so force default line spacing super.setLineSpacing(mLineSpacingExtra, mLineSpacingMultiplier); }
Example 20
Source File: BotHelpCell.java From TelePlus-Android with GNU General Public License v2.0 | 4 votes |
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); int maxWidth; if (AndroidUtilities.isTablet()) { maxWidth = (int) (AndroidUtilities.getMinTabletSide() * 0.7f); } else { maxWidth = (int) (Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) * 0.7f); } String lines[] = text.split("\n"); SpannableStringBuilder stringBuilder = new SpannableStringBuilder(); String help = LocaleController.getString("BotInfoTitle", R.string.BotInfoTitle); stringBuilder.append(help); stringBuilder.append("\n\n"); for (int a = 0; a < lines.length; a++) { stringBuilder.append(lines[a].trim()); if (a != lines.length - 1) { stringBuilder.append("\n"); } } MessageObject.addLinks(false, stringBuilder); stringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), 0, help.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); Emoji.replaceEmoji(stringBuilder, Theme.chat_msgTextPaint.getFontMetricsInt(), AndroidUtilities.dp(20), false); try { textLayout = new StaticLayout(stringBuilder, Theme.chat_msgTextPaint, maxWidth, 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))); } if (width > maxWidth) { width = maxWidth; } } catch (Exception e) { FileLog.e(e); } width += AndroidUtilities.dp(4 + 18); }