Example usage for android.graphics Paint measureText

List of usage examples for android.graphics Paint measureText

Introduction

In this page you can find the example usage for android.graphics Paint measureText.

Prototype

public float measureText(String text) 

Source Link

Document

Return the width of the text.

Usage

From source file:Main.java

private static String wrap(String s, float width, Paint p) {
    String[] str = s.split("\\s"); //regex
    StringBuilder smb = new StringBuilder(); //save memory
    smb.append(SYSTEM_NEWLINE);//from  w  ww .j a  v  a2 s . c  om
    for (int x = 0; x < str.length; x++) {
        float length = p.measureText(str[x]);
        String[] pieces = smb.toString().split(SYSTEM_NEWLINE);
        try {
            if (p.measureText(pieces[pieces.length - 1]) + length > width)
                smb.append(SYSTEM_NEWLINE);
        } catch (Exception e) {
        }
        smb.append(str[x] + " ");
    }
    return smb.toString().replaceFirst(SYSTEM_NEWLINE, "");
}

From source file:Main.java

protected static Object[] createWrappedLine(String block, Paint paint, float spaceOffset, float maxWidth) {
    float cacheWidth = maxWidth;
    float origMaxWidth = maxWidth;

    String line = "";

    for (String word : block.split("\\s")) {
        cacheWidth = paint.measureText(word);
        maxWidth -= cacheWidth;//from  w  ww  . j a va2  s  . co  m

        if (maxWidth <= 0) {
            return new Object[] { line, maxWidth + cacheWidth + spaceOffset };
        }

        line += word + " ";
        maxWidth -= spaceOffset;

    }

    if (paint.measureText(block) <= origMaxWidth) {
        return new Object[] { block, Float.MIN_VALUE };
    }

    return new Object[] { line, maxWidth };
}

From source file:Main.java

public static Bitmap text2Bitmap(String text, int color, float size) {
    if (TextUtils.isEmpty(text)) {
        return null;
    }/*from w  w  w  .  j av  a 2s  .  c o  m*/

    Paint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
    paint.setTextSize(size);
    paint.setColor(color);
    paint.setTextAlign(Paint.Align.LEFT);

    float baseline = -paint.ascent();
    int width = (int) (paint.measureText(text) + 0.5f);
    int height = (int) (baseline + paint.descent() + 0.5f);

    Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(image);
    canvas.drawText(text, 0, baseline, paint);
    return image;
}

From source file:Main.java

public static Bitmap addLabelToBitmap(Bitmap src, String label) {
    float densityFactor = Resources.getSystem().getDisplayMetrics().density;
    final float textPadding = src.getWidth() * 0.05f;

    Bitmap result = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(result);
    Paint textPaint = new Paint();
    textPaint.setAntiAlias(true);//from w ww.  ja  v a 2 s  .co  m
    textPaint.setTextSize(12 * densityFactor);
    textPaint.setColor(Color.WHITE);
    textPaint.setStrokeWidth(2 * densityFactor);
    textPaint.setShadowLayer(1 * densityFactor, 0, 0, Color.BLACK);

    float textWidth = textPaint.measureText(label);

    float scaleFactor = (src.getWidth() - textPadding * 2) / textWidth;

    canvas.drawBitmap(src, 0, 0, textPaint);

    canvas.save();
    canvas.scale(scaleFactor, scaleFactor);
    float textPosX = (src.getWidth() / scaleFactor - textWidth) / 2;
    float textPosY = (src.getHeight() - textPadding) / scaleFactor;

    canvas.drawText(label, textPosX, textPosY, textPaint);
    canvas.restore();
    return result;
}

From source file:Main.java

private static String justifyOperation(String s, float width, Paint p) {
    float holder = (float) (COMPLEXITY * Math.random());
    while (s.contains(Float.toString(holder))) {
        holder = (float) (COMPLEXITY * Math.random());
    }/*from   ww  w .j  a  v  a  2 s .c om*/
    String holder_string = Float.toString(holder);
    float lessThan = width;
    int timeOut = 100;
    int current = 0;
    while ((p.measureText(s) < lessThan) && (current < timeOut)) {
        s = s.replaceFirst(" ([^" + holder_string + "])", " " + holder_string + "$1");
        lessThan = (p.measureText(holder_string) + lessThan) - p.measureText(" ");
        current++;
    }
    String cleaned = s.replaceAll(holder_string, " ");
    return cleaned;
}

From source file:com.android.mail.ui.FolderDisplayer.java

public static void drawFolder(Canvas canvas, float x, float y, int width, int height, String name, int fgColor,
        int bgColor, FolderDisplayer.FolderDrawableResources res, BidiFormatter formatter, Paint paint) {
    canvas.save();//from  w w w  .  jav  a  2 s  . c  o m
    canvas.translate(x, y + res.folderVerticalOffset);

    // Draw the box.
    paint.setColor(bgColor);
    paint.setStyle(Paint.Style.FILL);
    final RectF rect = new RectF(0, 0, width, height);
    canvas.drawRoundRect(rect, res.folderRoundedCornerRadius, res.folderRoundedCornerRadius, paint);

    // Draw the text based on the language locale and layout direction.
    paint.setColor(fgColor);
    paint.setStyle(Paint.Style.FILL);

    // Compute the text/gradient indices
    final int textLength = (int) paint.measureText(name);
    final int gradientX0;
    final int gradientX1;
    final int textX;

    /***************************************************************************************************
     * width               - the actual folder chip rectangle.                                         *
     * textLength          - the length of the folder's full name (can be longer than                  *
     *                         the actual chip, which is what overflow gradient is for).               *
     * innerPadding        - the padding between the text and the chip edge.                           *
     * overflowPadding     - the padding between start of overflow and the chip edge.                  *
     *                                                                                                 *
     *                                                                                                 *
     * text is in a RTL language                                                                       *
     *                                                                                                 *
     *                   index-0                                                                       *
     *                      |<---------------------------- width ---------------------------->|        *
     *        |<-------------------------textLength------------------>|                       |        *
     *        |             |<----- overflowPadding ----->|                                   |        *
     *        |             |<- innerPadding ->|<-------->|<--------->|<- horizontalPadding ->|        *
     *       textX                            gX1        gX0                                           *
     *                                                                                                 *
     *                                                                                                 *
     * text is in a LTR language.                                                                      *
     *                                                                                                 *
     *     index-0                                                                                     *
     *        |<------------------------------ width ------------------------------->|                 *
     *        |                       |<-------------------------textLength-------------------->|      *
     *        |                                   |<-------- overflowPadding ------->|                 *
     *        |<- horizontalPadding ->|<--------->|<-------->|<- horizontalPadding ->|                 *
     *                              textX        gX0        gX1                                        *
     *                                                                                                 *
     **************************************************************************************************/
    if (formatter.isRtl(name)) {
        gradientX0 = res.overflowGradientPadding;
        gradientX1 = res.folderHorizontalPadding;
        textX = width - res.folderHorizontalPadding - textLength;
    } else {
        gradientX0 = width - res.overflowGradientPadding;
        gradientX1 = width - res.folderHorizontalPadding;
        textX = res.folderHorizontalPadding;
    }

    // Draw the text and the possible overflow gradient
    // Overflow happens when the text is longer than the chip width minus side paddings.
    if (textLength > width - 2 * res.folderHorizontalPadding) {
        final Shader shader = new LinearGradient(gradientX0, 0, gradientX1, 0, fgColor,
                Utils.getTransparentColor(fgColor), Shader.TileMode.CLAMP);
        paint.setShader(shader);
    }
    final int textY = height / 2 - (int) (paint.descent() + paint.ascent()) / 2;
    canvas.drawText(name, textX, textY, paint);
    paint.setShader(null);

    canvas.restore();
}

From source file:com.android.mail.ui.FolderDisplayer.java

/**
 * Helper function to calculate exactly how much space the displayed folders should take.
 * @param folders the set of folders to display.
 * @param maxCellWidth this signifies the absolute max for each folder cell, no exceptions.
 * @param maxLayoutWidth the view's layout width, aka how much space we have.
 * @param foldersInBetweenPadding the padding between folder chips.
 * @param foldersHorizontalPadding the padding between the edge of the chip and the text.
 * @param maxFolderCount the maximum number of folder chips to display.
 * @param paint work paint./*from   w  w w  .  ja  v  a2 s  . com*/
 * @return an array of integers that signifies the length of each folder chip.
 */
public static int[] measureFolderDimen(Set<Folder> folders, int maxCellWidth, int maxLayoutWidth,
        int foldersInBetweenPadding, int foldersHorizontalPadding, int maxFolderCount, Paint paint) {

    final int numDisplayedFolders = Math.min(maxFolderCount, folders.size());
    if (numDisplayedFolders == 0) {
        return new int[0];
    }

    // This variable is calculated based on the number of folders we are displaying
    final int maxAllowedCellSize = Math.min(maxCellWidth,
            (maxLayoutWidth - (numDisplayedFolders - 1) * foldersInBetweenPadding) / numDisplayedFolders);
    final int[] measurements = new int[numDisplayedFolders];

    int count = 0;
    int missingWidth = 0;
    int extraWidth = 0;
    for (Folder f : folders) {
        if (count > numDisplayedFolders - 1) {
            break;
        }

        final String folderString = f.name;
        final int neededWidth = (int) paint.measureText(folderString) + 2 * foldersHorizontalPadding;

        if (neededWidth > maxAllowedCellSize) {
            // What we can take from others is the minimum of the width we need to borrow
            // and the width we are allowed to borrow.
            final int borrowedWidth = Math.min(neededWidth - maxAllowedCellSize,
                    maxCellWidth - maxAllowedCellSize);
            final int extraWidthLeftover = extraWidth - borrowedWidth;
            if (extraWidthLeftover >= 0) {
                measurements[count] = Math.min(neededWidth, maxCellWidth);
                extraWidth = extraWidthLeftover;
            } else {
                measurements[count] = maxAllowedCellSize + extraWidth;
                extraWidth = 0;
            }
            missingWidth = -extraWidthLeftover;
        } else {
            extraWidth = maxAllowedCellSize - neededWidth;
            measurements[count] = neededWidth;
            if (missingWidth > 0) {
                if (extraWidth >= missingWidth) {
                    measurements[count - 1] += missingWidth;
                    extraWidth -= missingWidth;
                } else {
                    measurements[count - 1] += extraWidth;
                    extraWidth = 0;
                }
            }
            missingWidth = 0;
        }

        count++;
    }

    return measurements;
}

From source file:com.android.screenspeak.contextmenu.RadialMenuView.java

private static String getEllipsizedText(Paint paint, String title, float maxWidth) {
    final float textWidth = paint.measureText(title);
    if (textWidth <= maxWidth) {
        return title;
    }/*w  w w. j a  v a2s . c  om*/

    // Find the maximum length with an ellipsis.
    final float ellipsisWidth = paint.measureText(ELLIPSIS);
    final int length = paint.breakText(title, true, (maxWidth - ellipsisWidth), null);

    // Try to land on a word break.
    // TODO(AV): Use breaking iterator for better i18n support.
    final int space = title.lastIndexOf(' ', length);
    if (space > 0) {
        return title.substring(0, space) + ELLIPSIS;
    }

    // Otherwise, cut off characters.
    return title.substring(0, length) + ELLIPSIS;
}

From source file:com.android.talkback.contextmenu.RadialMenuView.java

private static String getEllipsizedText(Paint paint, String title, float maxWidth) {
    final float textWidth = paint.measureText(title);
    if (textWidth <= maxWidth) {
        return title;
    }/*from   w w  w  .j a va2  s .  c o m*/

    // Find the maximum length with an ellipsis.
    final float ellipsisWidth = paint.measureText(ELLIPSIS);
    final int length = paint.breakText(title, true, (maxWidth - ellipsisWidth), null);

    // Try to land on a word break.
    // TODO: Use breaking iterator for better i18n support.
    final int space = title.lastIndexOf(' ', length);
    if (space > 0) {
        return title.substring(0, space) + ELLIPSIS;
    }

    // Otherwise, cut off characters.
    return title.substring(0, length) + ELLIPSIS;
}

From source file:org.cocos2dx.lib.Cocos2dxBitmap.java

private static String[] splitString(String content, int maxHeight, int maxWidth, Paint paint) {
    String[] lines = content.split("\\n");
    String[] ret = null;/*from www  .j  a v a2s.  c  o  m*/
    FontMetricsInt fm = paint.getFontMetricsInt();
    int heightPerLine = (int) Math.ceil(fm.bottom - fm.top);
    int maxLines = maxHeight / heightPerLine;

    if (maxWidth != 0) {
        LinkedList<String> strList = new LinkedList<String>();
        for (String line : lines) {
            /*
             * The width of line is exceed maxWidth, should divide it into
             * two or more lines.
             */
            int lineWidth = (int) Math.ceil(paint.measureText(line));
            if (lineWidth > maxWidth) {
                strList.addAll(divideStringWithMaxWidth(paint, line, maxWidth));
            } else {
                strList.add(line);
            }

            /*
             * Should not exceed the max height;
             */
            if (maxLines > 0 && strList.size() >= maxLines) {
                break;
            }
        }

        /*
         * Remove exceeding lines
         */
        if (maxLines > 0 && strList.size() > maxLines) {
            while (strList.size() > maxLines) {
                strList.removeLast();
            }
        }

        ret = new String[strList.size()];
        strList.toArray(ret);
    } else if (maxHeight != 0 && lines.length > maxLines) {
        /*
         * Remove exceeding lines
         */
        LinkedList<String> strList = new LinkedList<String>();
        for (int i = 0; i < maxLines; i++) {
            strList.add(lines[i]);
        }
        ret = new String[strList.size()];
        strList.toArray(ret);
    } else {
        ret = lines;
    }

    return ret;
}