Example usage for android.text StaticLayout StaticLayout

List of usage examples for android.text StaticLayout StaticLayout

Introduction

In this page you can find the example usage for android.text StaticLayout StaticLayout.

Prototype

@Deprecated
public StaticLayout(CharSequence source, TextPaint paint, int width, Alignment align, float spacingmult,
        float spacingadd, boolean includepad) 

Source Link

Usage

From source file:Main.java

static int getTextHeight(CharSequence text, TextPaint paint, int targetWidth, float textSize) {
    TextPaint paintCopy = new TextPaint(paint);
    paintCopy.setTextSize(textSize);/*www  . ja va2 s  .  c o m*/
    StaticLayout layout = new StaticLayout(text, paintCopy, (int) targetWidth, Layout.Alignment.ALIGN_NORMAL,
            1.0f, 0.0f, true);
    return layout.getHeight();
}

From source file:Main.java

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);//from   w  ww  .  j  a  va 2s . c  o  m
    return layout.getLineCount();
}

From source file:Main.java

/**
 * Recursive binary search to find the best size for the text.
 *///from   w w w. j  a  v a 2  s  .  c  o m
private static float getAutofitTextSize(CharSequence text, TextPaint paint, float targetWidth, int maxLines,
        float low, float high, float precision, DisplayMetrics displayMetrics) {
    float mid = (low + high) / 2.0f;
    int lineCount = 1;
    StaticLayout layout = null;

    paint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, mid, displayMetrics));

    if (maxLines != 1) {
        layout = new StaticLayout(text, paint, (int) targetWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f,
                true);
        lineCount = layout.getLineCount();
    }

    if (SPEW)
        Log.d(TAG, "low=" + low + " high=" + high + " mid=" + mid + " target=" + targetWidth + " maxLines="
                + maxLines + " lineCount=" + lineCount);

    if (lineCount > maxLines) {
        // For the case that `text` has more newline characters than `maxLines`.
        if ((high - low) < precision) {
            return low;
        }
        return getAutofitTextSize(text, paint, targetWidth, maxLines, low, mid, precision, displayMetrics);
    } else if (lineCount < maxLines) {
        return getAutofitTextSize(text, paint, targetWidth, maxLines, mid, high, precision, displayMetrics);
    } else {
        float maxLineWidth = 0;
        if (maxLines == 1) {
            maxLineWidth = paint.measureText(text, 0, text.length());
        } else {
            for (int i = 0; i < lineCount; i++) {
                if (layout.getLineWidth(i) > maxLineWidth) {
                    maxLineWidth = layout.getLineWidth(i);
                }
            }
        }

        if ((high - low) < precision) {
            return low;
        } else if (maxLineWidth > targetWidth) {
            return getAutofitTextSize(text, paint, targetWidth, maxLines, low, mid, precision, displayMetrics);
        } else if (maxLineWidth < targetWidth) {
            return getAutofitTextSize(text, paint, targetWidth, maxLines, mid, high, precision, displayMetrics);
        } else {
            return mid;
        }
    }
}

From source file:com.achillesrasquinha.biblegenerator.ImageGenerator.java

public Bitmap getBitmap(String title, String subtitle, String text) {
    Bitmap bitmap = Bitmap.createBitmap(mImageSize.x, mImageSize.y, Bitmap.Config.ARGB_8888);
    //convert bitmap to card view background color
    bitmap.eraseColor(ContextCompat.getColor(mContext, R.color.cardview_light_background));

    Canvas canvas = new Canvas(bitmap);

    //title//w  w  w .j a  v  a2 s  .c  om
    mTextPaint.setTextSize(mSizeTitle);
    mTextPaint.setColor(mColor1);
    canvas.drawText(title, mX, mYTitle, mTextPaint);

    //subtitle
    mTextPaint.setTextSize(mSizeSubtitle);
    mTextPaint.setColor(mColor2);
    canvas.drawText(subtitle, mX, mYSubtitle, mTextPaint);

    //since text needs to be wrapped, using a StaticLayout
    mTextPaint.setColor(mColor3);
    //text size same as subtitle size
    StaticLayout layout = new StaticLayout(text, mTextPaint, mImageSize.x - 2 * mX,
            Layout.Alignment.ALIGN_NORMAL, 1.0f, mLineSpacing, false);
    //16dp padding as per material design guidelines
    canvas.translate(mX, mYSubtitle + mX);
    layout.draw(canvas);

    return bitmap;
}

From source file:org.telegram.ui.Cells.BotHelpCell.java

public void setText(String text) {
    if (text == null || text.length() == 0) {
        setVisibility(GONE);//from  w w w .  j a  v  a2s .co  m
        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);
}

From source file:org.telegram.ui.Cells.HintDialogCell.java

public void checkUnreadCounter(int mask) {
    if (mask != 0 && (mask & MessagesController.UPDATE_MASK_READ_DIALOG_MESSAGE) == 0
            && (mask & MessagesController.UPDATE_MASK_NEW_MESSAGE) == 0) {
        return;/*from  w ww  .  j  a v  a 2 s. c  om*/
    }
    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;
    }
}

From source file:com.savvasdalkitsis.betwixt.demo.InterpolatorView.java

public void setDescription(String description) {
    this.description = description;
    StaticLayout textLayout = new StaticLayout(description, textPaint, Integer.MAX_VALUE,
            Layout.Alignment.ALIGN_CENTER, 0, 0, false);
    textHeight = textLayout.getHeight();
}

From source file:org.telegram.ui.Cells.ContextLinkCell.java

@SuppressLint("DrawAllocation")
@Override//from  ww w  . j a  v a  2 s  . co m
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    drawLinkImageView = false;
    descriptionLayout = null;
    titleLayout = null;
    linkLayout = null;
    linkY = AndroidUtilities.dp(27);

    if (inlineResult == null && documentAttach == null) {
        setMeasuredDimension(AndroidUtilities.dp(100), AndroidUtilities.dp(100));
        return;
    }

    int viewWidth = MeasureSpec.getSize(widthMeasureSpec);
    int maxWidth = viewWidth - AndroidUtilities.dp(AndroidUtilities.leftBaseline) - AndroidUtilities.dp(8);

    TLRPC.PhotoSize currentPhotoObject = null;
    TLRPC.PhotoSize currentPhotoObjectThumb = null;
    ArrayList<TLRPC.PhotoSize> photoThumbs = null;
    String url = null;

    if (documentAttach != null) {
        photoThumbs = new ArrayList<>();
        photoThumbs.add(documentAttach.thumb);
    } else if (inlineResult != null && inlineResult.photo != null) {
        photoThumbs = new ArrayList<>(inlineResult.photo.sizes);
    }

    if (!mediaWebpage && inlineResult != null) {
        if (inlineResult.title != null) {
            try {
                int width = (int) Math.ceil(titleTextPaint.measureText(inlineResult.title));
                CharSequence titleFinal = TextUtils.ellipsize(
                        Emoji.replaceEmoji(inlineResult.title.replace('\n', ' '),
                                titleTextPaint.getFontMetricsInt(), AndroidUtilities.dp(15), false),
                        titleTextPaint, Math.min(width, maxWidth), TextUtils.TruncateAt.END);
                titleLayout = new StaticLayout(titleFinal, titleTextPaint, maxWidth + AndroidUtilities.dp(4),
                        Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
            letterDrawable.setTitle(inlineResult.title);
        }

        if (inlineResult.description != null) {
            try {
                descriptionLayout = ChatMessageCell.generateStaticLayout(
                        Emoji.replaceEmoji(inlineResult.description, descriptionTextPaint.getFontMetricsInt(),
                                AndroidUtilities.dp(13), false),
                        descriptionTextPaint, maxWidth, maxWidth, 0, 3);
                if (descriptionLayout.getLineCount() > 0) {
                    linkY = descriptionY + descriptionLayout.getLineBottom(descriptionLayout.getLineCount() - 1)
                            + AndroidUtilities.dp(1);
                }
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
        }

        if (inlineResult.url != null) {
            try {
                int width = (int) Math.ceil(descriptionTextPaint.measureText(inlineResult.url));
                CharSequence linkFinal = TextUtils.ellipsize(inlineResult.url.replace('\n', ' '),
                        descriptionTextPaint, Math.min(width, maxWidth), TextUtils.TruncateAt.MIDDLE);
                linkLayout = new StaticLayout(linkFinal, descriptionTextPaint, maxWidth,
                        Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
        }
    }

    String ext = null;
    if (documentAttach != null) {
        if (MessageObject.isGifDocument(documentAttach)) {
            currentPhotoObject = documentAttach.thumb;
        } else if (MessageObject.isStickerDocument(documentAttach)) {
            currentPhotoObject = documentAttach.thumb;
            ext = "webp";
        } else {
            if (documentAttachType != DOCUMENT_ATTACH_TYPE_MUSIC
                    && documentAttachType != DOCUMENT_ATTACH_TYPE_AUDIO) {
                currentPhotoObject = documentAttach.thumb;
            }
        }
    } else if (inlineResult != null && inlineResult.photo != null) {
        currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(photoThumbs,
                AndroidUtilities.getPhotoSize(), true);
        currentPhotoObjectThumb = FileLoader.getClosestPhotoSizeWithSize(photoThumbs, 80);
        if (currentPhotoObjectThumb == currentPhotoObject) {
            currentPhotoObjectThumb = null;
        }
    }
    if (inlineResult != null) {
        if (inlineResult.content_url != null) {
            if (inlineResult.type != null) {
                if (inlineResult.type.startsWith("gif")) {
                    if (documentAttachType != DOCUMENT_ATTACH_TYPE_GIF) {
                        url = inlineResult.content_url;
                        documentAttachType = DOCUMENT_ATTACH_TYPE_GIF;
                    }
                } else if (inlineResult.type.equals("photo")) {
                    url = inlineResult.thumb_url;
                    if (url == null) {
                        url = inlineResult.content_url;
                    }
                }
            }
        }
        if (url == null && inlineResult.thumb_url != null) {
            url = inlineResult.thumb_url;
        }
    }
    if (url == null && currentPhotoObject == null && currentPhotoObjectThumb == null) {
        if (inlineResult.send_message instanceof TLRPC.TL_botInlineMessageMediaVenue
                || inlineResult.send_message instanceof TLRPC.TL_botInlineMessageMediaGeo) {
            double lat = inlineResult.send_message.geo.lat;
            double lon = inlineResult.send_message.geo._long;
            url = String.format(Locale.US,
                    "https://maps.googleapis.com/maps/api/staticmap?center=%f,%f&zoom=15&size=72x72&maptype=roadmap&scale=%d&markers=color:red|size:small|%f,%f&sensor=false",
                    lat, lon, Math.min(2, (int) Math.ceil(AndroidUtilities.density)), lat, lon);
        }
    }

    int width;
    int w = 0;
    int h = 0;

    if (documentAttach != null) {
        for (int b = 0; b < documentAttach.attributes.size(); b++) {
            TLRPC.DocumentAttribute attribute = documentAttach.attributes.get(b);
            if (attribute instanceof TLRPC.TL_documentAttributeImageSize
                    || attribute instanceof TLRPC.TL_documentAttributeVideo) {
                w = attribute.w;
                h = attribute.h;
                break;
            }
        }
    }
    if (w == 0 || h == 0) {
        if (currentPhotoObject != null) {
            if (currentPhotoObjectThumb != null) {
                currentPhotoObjectThumb.size = -1;
            }
            w = currentPhotoObject.w;
            h = currentPhotoObject.h;
        } else if (inlineResult != null) {
            w = inlineResult.w;
            h = inlineResult.h;
        }
    }
    if (w == 0 || h == 0) {
        w = h = AndroidUtilities.dp(80);
    }
    if (documentAttach != null || currentPhotoObject != null || url != null) {
        String currentPhotoFilter;
        String currentPhotoFilterThumb = "52_52_b";

        if (mediaWebpage) {
            width = (int) (w / (h / (float) AndroidUtilities.dp(80)));
            if (documentAttachType == DOCUMENT_ATTACH_TYPE_GIF) {
                currentPhotoFilterThumb = currentPhotoFilter = String.format(Locale.US, "%d_%d_b",
                        (int) (width / AndroidUtilities.density), 80);
            } else {
                currentPhotoFilter = String.format(Locale.US, "%d_%d", (int) (width / AndroidUtilities.density),
                        80);
                currentPhotoFilterThumb = currentPhotoFilter + "_b";
            }
        } else {
            currentPhotoFilter = "52_52";
        }
        linkImageView.setAspectFit(documentAttachType == DOCUMENT_ATTACH_TYPE_STICKER);

        if (documentAttachType == DOCUMENT_ATTACH_TYPE_GIF) {
            if (documentAttach != null) {
                linkImageView.setImage(documentAttach, null,
                        currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilter,
                        documentAttach.size, ext, false);
            } else {
                linkImageView.setImage(null, url, null, null,
                        currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilter, -1,
                        ext, true);
            }
        } else {
            if (currentPhotoObject != null) {
                linkImageView.setImage(currentPhotoObject.location, currentPhotoFilter,
                        currentPhotoObjectThumb != null ? currentPhotoObjectThumb.location : null,
                        currentPhotoFilterThumb, currentPhotoObject.size, ext, false);
            } else {
                linkImageView.setImage(null, url, currentPhotoFilter, null,
                        currentPhotoObjectThumb != null ? currentPhotoObjectThumb.location : null,
                        currentPhotoFilterThumb, -1, ext, true);
            }
        }
        drawLinkImageView = true;
    }

    if (mediaWebpage) {
        setBackgroundDrawable(null);
        width = viewWidth;
        int height = MeasureSpec.getSize(heightMeasureSpec);
        if (height == 0) {
            height = AndroidUtilities.dp(100);
        }
        setMeasuredDimension(width, height);
        int x = (width - AndroidUtilities.dp(24)) / 2;
        int y = (height - AndroidUtilities.dp(24)) / 2;
        radialProgress.setProgressRect(x, y, x + AndroidUtilities.dp(24), y + AndroidUtilities.dp(24));
        linkImageView.setImageCoords(0, 0, width, height);
    } else {
        setBackgroundResource(R.drawable.list_selector);
        int height = 0;
        if (titleLayout != null && titleLayout.getLineCount() != 0) {
            height += titleLayout.getLineBottom(titleLayout.getLineCount() - 1);
        }
        if (descriptionLayout != null && descriptionLayout.getLineCount() != 0) {
            height += descriptionLayout.getLineBottom(descriptionLayout.getLineCount() - 1);
        }
        if (linkLayout != null && linkLayout.getLineCount() > 0) {
            height += linkLayout.getLineBottom(linkLayout.getLineCount() - 1);
        }
        height = Math.max(AndroidUtilities.dp(52), height);
        setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),
                Math.max(AndroidUtilities.dp(68), height + AndroidUtilities.dp(16)) + (needDivider ? 1 : 0));

        int maxPhotoWidth = AndroidUtilities.dp(52);
        int x = LocaleController.isRTL
                ? MeasureSpec.getSize(widthMeasureSpec) - AndroidUtilities.dp(8) - maxPhotoWidth
                : AndroidUtilities.dp(8);
        letterDrawable.setBounds(x, AndroidUtilities.dp(8), x + maxPhotoWidth, AndroidUtilities.dp(60));
        linkImageView.setImageCoords(x, AndroidUtilities.dp(8), maxPhotoWidth, maxPhotoWidth);
        if (documentAttachType == DOCUMENT_ATTACH_TYPE_AUDIO
                || documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC) {
            radialProgress.setProgressRect(x + AndroidUtilities.dp(4), AndroidUtilities.dp(12),
                    x + AndroidUtilities.dp(48), AndroidUtilities.dp(56));
        }
    }
}

From source file:org.telegram.ui.Cells.AboutLinkCell.java

@SuppressLint("DrawAllocation")
@Override//from  w w w . j  a va 2  s . co  m
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    textLayout = new StaticLayout(stringBuilder, textPaint,
            MeasureSpec.getSize(widthMeasureSpec) - AndroidUtilities.dp(71 + 16), Layout.Alignment.ALIGN_NORMAL,
            1.0f, 0.0f, false);
    super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY),
            MeasureSpec.makeMeasureSpec(textLayout.getHeight() + AndroidUtilities.dp(16), MeasureSpec.EXACTLY));
}

From source file:com.coreform.open.android.formidablevalidation.SetErrorHandler.java

private void chooseSize(PopupWindow pop, CharSequence text, TextView tv) {
    int wid = tv.getPaddingLeft() + tv.getPaddingRight();
    int ht = tv.getPaddingTop() + tv.getPaddingBottom();

    //com.android.internal.R.dimen.textview_error_popup_default_width introduced after Gingerbread, only has one variant (240dip)
    int defaultWidthInPixels = mContext.getResources()
            .getDimensionPixelSize(R.dimen.textview_error_popup_default_width);
    Layout l = new StaticLayout(text, tv.getPaint(), defaultWidthInPixels, Layout.Alignment.ALIGN_NORMAL, 1, 0,
            true);//from  w w w. j  a  v  a  2s.  c o m

    float max = 0;
    for (int i = 0; i < l.getLineCount(); i++) {
        max = Math.max(max, l.getLineWidth(i));
    }

    if (DEBUG)
        Log.d(TAG, "max: " + max + ", height: " + l.getHeight());

    /*
     * Now set the popup size to be big enough for the text plus the border.
     */
    pop.setWidth(wid + (int) Math.ceil(max));
    pop.setHeight(ht + l.getHeight()); //TODO: buggy (the 2 shouldnt need to be there)
}