Example usage for android.graphics Paint getTextBounds

List of usage examples for android.graphics Paint getTextBounds

Introduction

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

Prototype

public void getTextBounds(char[] text, int index, int count, Rect bounds) 

Source Link

Document

Return in bounds (allocated by the caller) the smallest rectangle that encloses all of the characters, with an implied origin at (0,0).

Usage

From source file:com.kabootar.GlassMemeGenerator.ImageOverlay.java

/**
 * Draws the given string centered, as big as possible, on either the top or
 * bottom 20% of the image given./*w  ww  .  ja  v a  2 s.  c  o m*/
 */
private static void drawStringCentered(Canvas g, String text, Bitmap image, boolean top, Context baseContext)
        throws InterruptedException {
    if (text == null)
        text = "";

    int height = 0;
    int fontSize = MAX_FONT_SIZE;
    int maxCaptionHeight = image.getHeight() / 5;
    int maxLineWidth = image.getWidth() - SIDE_MARGIN * 2;
    String formattedString = "";
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

    Paint stkPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    stkPaint.setStyle(STROKE);
    stkPaint.setStrokeWidth(8);
    stkPaint.setColor(Color.BLACK);

    //Typeface tf = Typeface.create("Arial", Typeface.BOLD);
    Typeface tf = Typeface.createFromAsset(baseContext.getAssets(), "fonts/impact.ttf");

    paint.setTypeface(tf);
    stkPaint.setTypeface(tf);
    do {

        paint.setTextSize(fontSize);

        // first inject newlines into the text to wrap properly
        StringBuilder sb = new StringBuilder();
        int left = 0;
        int right = text.length() - 1;
        while (left < right) {

            String substring = text.substring(left, right + 1);
            Rect stringBounds = new Rect();
            paint.getTextBounds(substring, 0, substring.length(), stringBounds);
            while (stringBounds.width() > maxLineWidth) {
                if (Thread.currentThread().isInterrupted()) {
                    throw new InterruptedException();
                }

                // look for a space to break the line
                boolean spaceFound = false;
                for (int i = right; i > left; i--) {
                    if (text.charAt(i) == ' ') {
                        right = i - 1;
                        spaceFound = true;
                        break;
                    }
                }
                substring = text.substring(left, right + 1);
                paint.getTextBounds(substring, 0, substring.length(), stringBounds);

                // If we're down to a single word and we are still too wide,
                // the font is just too big.
                if (!spaceFound && stringBounds.width() > maxLineWidth) {
                    break;
                }
            }
            sb.append(substring).append("\n");
            left = right + 2;
            right = text.length() - 1;
        }

        formattedString = sb.toString();

        // now determine if this font size is too big for the allowed height
        height = 0;
        for (String line : formattedString.split("\n")) {
            Rect stringBounds = new Rect();
            paint.getTextBounds(line, 0, line.length(), stringBounds);
            height += stringBounds.height();
        }
        fontSize--;
    } while (height > maxCaptionHeight);

    // draw the string one line at a time
    int y = 0;
    if (top) {
        y = TOP_MARGIN;
    } else {
        y = image.getHeight() - height - BOTTOM_MARGIN;
    }
    for (String line : formattedString.split("\n")) {
        // Draw each string twice for a shadow effect
        Rect stringBounds = new Rect();
        paint.getTextBounds(line, 0, line.length(), stringBounds);
        //paint.setColor(Color.BLACK);
        //g.drawText(line, (image.getWidth() - (int) stringBounds.width()) / 2 + 2, y + stringBounds.height() + 2, paint);

        paint.setColor(Color.WHITE);
        g.drawText(line, (image.getWidth() - (int) stringBounds.width()) / 2, y + stringBounds.height(), paint);

        //stroke
        Rect strokeBounds = new Rect();
        stkPaint.setTextSize(fontSize);
        stkPaint.getTextBounds(line, 0, line.length(), strokeBounds);
        g.drawText(line, (image.getWidth() - (int) strokeBounds.width()) / 2, y + strokeBounds.height(),
                stkPaint);

        y += stringBounds.height();
    }
}

From source file:com.android.cts.verifier.managedprovisioning.NfcTestActivity.java

/**
 * Creates a Bitmap image that contains red on white text with a specified margin.
 * @param text Text to be displayed in the image.
 * @return A Bitmap image with the above specification.
 *///from   ww  w.  j a  v a 2 s  . c  o m
private Bitmap createSampleImage(String text) {
    Paint paint = new Paint();
    paint.setStyle(Paint.Style.FILL);
    paint.setTextSize(TEXT_SIZE);
    Rect rect = new Rect();
    paint.getTextBounds(text, 0, text.length(), rect);
    int w = 2 * MARGIN + rect.right - rect.left;
    int h = 2 * MARGIN + rect.bottom - rect.top;
    Bitmap dest = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas();
    canvas.setBitmap(dest);
    paint.setColor(Color.WHITE);
    canvas.drawPaint(paint);
    paint.setColor(Color.RED);
    canvas.drawText(text, MARGIN - rect.left, MARGIN - rect.top, paint);
    return dest;
}

From source file:com.huahcoding.metrojam.BackTrackActivity.java

/**
 * This is where we can add markers or lines, add listeners or move the camera. In this case, we
 * just add a marker near Africa.//from  w  w  w . j a  va2  s .  c o m
 * <p>
 * This should only be called once and when we are sure that {@link #mMap} is not null.
 */
private void setUpMap() {
    mMap.getUiSettings().setZoomControlsEnabled(false);

    // Show Lima
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(chileLatLng, 15));

    mMap.setOnMapLongClickListener(this);
    mMap.setMyLocationEnabled(true);
    mMap.setTrafficEnabled(true);

    // Instantiates a new Polyline object and adds points to define a rectangle
    PolylineOptions rectOptions = new PolylineOptions();
    double[] route = RouteTestData.getChilePoints3();
    for (int i = 0; i < route.length - 1; i += 2) {
        LatLng ll = new LatLng(route[i], route[i + 1]);
        if (i > 1) {
            double lat = (route[i] + route[i - 2]) / 2.0;
            double lng = (route[i + 1] + route[i + 1 - 2]) / 2.0;
            double dist = distance(route[i], route[i + 1], route[i - 2], route[i + 1 - 2]);
            String pretty = getPrettyDistance(dist);

            LatLng ll2 = new LatLng(lat, lng);
            String strText = pretty;
            Rect boundsText = new Rect();
            Paint textPaint = new Paint();
            textPaint.setTextSize(18);
            textPaint.getTextBounds(strText, 0, strText.length(), boundsText);

            textPaint.setColor(Color.RED);

            Bitmap.Config conf = Bitmap.Config.ARGB_8888;
            Bitmap bmpText = Bitmap.createBitmap(boundsText.width() * 3, boundsText.height(), conf);

            Canvas canvasText = new Canvas(bmpText);
            canvasText.drawText(strText, canvasText.getWidth() / 2, canvasText.getHeight(), textPaint);

            MarkerOptions markerOptions = new MarkerOptions().position(ll2)
                    .icon(BitmapDescriptorFactory.fromBitmap(bmpText)).anchor(0.5f, 1);
            mMap.addMarker(markerOptions);
        }
        rectOptions.add(ll);
    }
    //         rectOptions.
    // Get back the mutable Polyline
    mMap.addPolyline(rectOptions);
}

From source file:com.g_node.gca.abstracts.AbstractCursorAdapter.java

@Override
public void bindView(View view, Context context, Cursor cursor) {
    // TODO Auto-generated method stub
    /*// w  w w  .  ja v  a  2  s .c o  m
     * TextView for showing Title
     */
    TextView title = (TextView) view.findViewById(R.id.abTitle);
    title.setText(cursor.getString(cursor.getColumnIndexOrThrow("TITLE")));
    /*
     * TextView for showing Topic
     */
    TextView topic = (TextView) view.findViewById(R.id.abTopic);
    topic.setText(cursor.getString(cursor.getColumnIndexOrThrow("TOPIC")));
    /*
     * TextView for Showing Type
     */
    TextView type = (TextView) view.findViewById(R.id.abType);
    int absSortID = cursor.getInt(cursor.getColumnIndexOrThrow("SORTID"));

    if (absSortID != 0) {
        int groupid = ((absSortID & (0xFFFF << 16)) >> 16);

        switch (groupid) {
        case 0:
            type.setText("Invited Talk");
            type.setBackgroundColor(Color.parseColor("#33B5E5"));
            break;

        case 1:
            type.setText("Contributed Talk");
            type.setBackgroundColor(Color.parseColor("#ef4172"));
            break;

        case 2:
            type.setText("Poster");
            type.setBackgroundColor(Color.parseColor("#AA66CC"));
            break;

        case 3:
            type.setText("Poster");
            type.setBackgroundColor(Color.parseColor("#AA66CC"));
            break;
        default:
            break;
        }

        //absSortID.append("Group ID: " + get_groupid_str(groupid));

    } else {
        //type.setVisibility(View.GONE);
        type.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4);
        type.setVisibility(View.INVISIBLE);
    }

    /*
    Following piece of commented code isn't needed as Abstract Type is 
    selected now based on GroupID. Previously it was being selected based on 'isTalk' field
    but now it's selected on basis of GroupID extracted from SortID. 
            
    String typeText = cursor.getString(cursor.getColumnIndexOrThrow("TYPE"));
    type.setText(typeText.toUpperCase());
            
    if(typeText.compareToIgnoreCase("poster") == 0) {
       type.setBackgroundColor(Color.parseColor("#AA66CC"));
    } else {
       type.setBackgroundColor(Color.parseColor("#33B5E5"));
    }
    */

    /*
     * _id for getting Author Names
     */
    String value = cursor.getString(cursor.getColumnIndexOrThrow("_id"));

    String authorNamesQuery = "SELECT ABSTRACT_UUID, AUTHORS_DETAILS.AUTHOR_UUID, AUTHORS_DETAILS.AUTHOR_FIRST_NAME, AUTHOR_MIDDLE_NAME, AUTHOR_LAST_NAME, AUTHOR_EMAIL, ABSTRACT_AUTHOR_POSITION_AFFILIATION.AUTHOR_POSITION as _aPos FROM ABSTRACT_AUTHOR_POSITION_AFFILIATION LEFT OUTER JOIN AUTHORS_DETAILS USING (AUTHOR_UUID) WHERE ABSTRACT_UUID = '"
            + value + "' ORDER BY _aPos;";
    cursorOne = DatabaseHelper.database.rawQuery(authorNamesQuery, null);

    if (cursorOne != null) {
        cursorOne.moveToFirst();
        /*
         * Name format will be like this A, B & C or A,B,C & D. So, if the
         * name is the last name. We should use '&' before the name
         */
        do {

            if (cursorOne.getPosition() == 0) {
                /*
                 * First data
                 */
                getName = cursorOne.getString(cursorOne.getColumnIndexOrThrow("AUTHOR_FIRST_NAME")) + " "
                        + cursorOne.getString(cursorOne.getColumnIndexOrThrow("AUTHOR_LAST_NAME"));
            } else if (cursorOne.isLast()) {
                /*
                 * Last Data
                 */
                getName = getName + " & "
                        + cursorOne.getString(cursorOne.getColumnIndexOrThrow("AUTHOR_FIRST_NAME")) + " "
                        + cursorOne.getString(cursorOne.getColumnIndexOrThrow("AUTHOR_LAST_NAME"));
            } else {
                getName = getName + " , "
                        + cursorOne.getString(cursorOne.getColumnIndexOrThrow("AUTHOR_FIRST_NAME")) + " "
                        + cursorOne.getString(cursorOne.getColumnIndexOrThrow("AUTHOR_LAST_NAME"));

            }

        } while (cursorOne.moveToNext());
    }

    /*
     * TextView for Author Names
     */
    TextView authorNames = (TextView) view.findViewById(R.id.absAuthorNames);
    /*
     * Get Width
     */
    WindowManager WinMgr = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    @SuppressWarnings("deprecation")
    int displayWidth = WinMgr.getDefaultDisplay().getWidth();
    Paint paint = new Paint();
    Rect bounds = new Rect();
    int text_width = 0;
    paint.getTextBounds(getName, 0, getName.length(), bounds);
    /*
     * Getting Text Width
     */
    text_width = bounds.width();
    /*
     * If Text Width is greater than Display Width Then show First Name et
     * al.
     */
    if (text_width > displayWidth) {
        String output = getName.split(",")[0] + " et al. ";
        authorNames.setText(output);

    } else {
        /*
         * Name Format will be like this If the Name is Yasir Adnan So,It
         * will be Y.Adnan
         */
        authorNames.setText(getName.replaceAll("((?:^|[^A-Z.])[A-Z])[a-z]*\\s(?=[A-Z])", "$1."));
    }
}

From source file:org.stockchart.core.Appearance.java

public SizeF measureTextSize(String text, Paint p, boolean applyText) {
    if (applyText)
        this.applyText(p);

    p.getTextBounds(text, 0, text.length(), fTempRect);

    return new SizeF(fTempRect.width(), fTempRect.height());
}

From source file:pl.mg6.newmaps.demo.MarkersExampleActivity.java

private Bitmap prepareBitmap() {
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.arrow_left);
    bitmap = bitmap.copy(Config.ARGB_8888, true);
    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint();
    paint.setAntiAlias(true);/*from   w  w w . j a  v a 2  s  . c o m*/
    paint.setColor(Color.WHITE);
    paint.setTextAlign(Align.CENTER);
    paint.setTextSize(getResources().getDimension(R.dimen.text_size));
    String text = "mg6";
    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, text.length(), bounds);
    float x = bitmap.getWidth() / 2.0f;
    float y = (bitmap.getHeight() - bounds.height()) / 2.0f - bounds.top;
    canvas.drawText(text, x, y, paint);
    return bitmap;
}

From source file:im.neon.util.VectorUtils.java

/**
 * Create an avatar bitmap from a text./*w w  w.jav  a 2 s  . com*/
 *
 * @param backgroundColor the background color.
 * @param text            the text to display.
 * @param pixelsSide      the avatar side in pixels
 * @return the generated bitmap
 */
private static Bitmap createAvatar(int backgroundColor, String text, int pixelsSide) {
    android.graphics.Bitmap.Config bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;

    Bitmap bitmap = Bitmap.createBitmap(pixelsSide, pixelsSide, bitmapConfig);
    Canvas canvas = new Canvas(bitmap);

    canvas.drawColor(backgroundColor);

    // prepare the text drawing
    Paint textPaint = new Paint();
    textPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
    textPaint.setColor(Color.WHITE);
    // the text size is proportional to the avatar size.
    // by default, the avatar size is 42dp, the text size is 28 dp (not sp because it has to be fixed).
    textPaint.setTextSize(pixelsSide * 2 / 3);

    // get its size
    Rect textBounds = new Rect();
    textPaint.getTextBounds(text, 0, text.length(), textBounds);

    // draw the text in center
    canvas.drawText(text, (canvas.getWidth() - textBounds.width() - textBounds.left) / 2,
            (canvas.getHeight() + textBounds.height() - textBounds.bottom) / 2, textPaint);

    // Return the avatar
    return bitmap;
}

From source file:com.layer_net.stepindicator.StepIndicator.java

private void drawTextCentred(Canvas canvas, Paint paint, String text, float cx, float cy) {
    paint.getTextBounds(text, 0, text.length(), textBounds);
    canvas.drawText(text, cx, cy - textBounds.exactCenterY(), paint);
}

From source file:net.exclaimindustries.geohashdroid.wiki.WikiPictureEditor.java

private static void drawStrings(String[] strings, Canvas c, Paint textPaint, Paint backgroundPaint) {
    // FIXME: The math here is ugly and blunt and probably not too
    // efficient or flexible.  It might even fail.  This needs to be
    // fixed and made less-ugly later.

    // We need SOME strings.  If we've got nothing, bail out.
    if (strings.length < 1)
        return;/*from  www.  j a  v  a 2 s.co m*/

    // First, init our variables.  This is as good a place as any to do so.
    Rect textBounds = new Rect();
    int[] heights = new int[strings.length];
    int totalHeight = INFOBOX_MARGIN * 2;
    int longestWidth = 0;

    // Now, loop through the strings, adding to the height and keeping track
    // of the longest width.
    int i = 0;
    for (String s : strings) {
        textPaint.getTextBounds(s, 0, s.length(), textBounds);
        if (textBounds.width() > longestWidth)
            longestWidth = textBounds.width();
        totalHeight += textBounds.height();
        heights[i] = textBounds.height();
        i++;
    }

    // Now, we have us a rectangle.  Draw that.
    Rect drawBounds = new Rect(c.getWidth() - longestWidth - (INFOBOX_MARGIN * 2), 0, c.getWidth(),
            totalHeight);

    c.drawRect(drawBounds, backgroundPaint);

    // Now, place each of the strings.  We'll assume the topmost one is in
    // index 0.  They should all be left-justified, too.
    i = 0;
    int curHeight = 0;
    for (String s : strings) {
        Log.d(DEBUG_TAG, "Drawing " + s + " at " + (drawBounds.left + INFOBOX_MARGIN) + ","
                + (INFOBOX_MARGIN + (INFOBOX_PADDING * (i + 1)) + curHeight));
        c.drawText(s, drawBounds.left + INFOBOX_MARGIN,
                INFOBOX_MARGIN + (INFOBOX_PADDING * (i + 1)) + curHeight, textPaint);
        curHeight += heights[i];
        i++;
    }
}

From source file:foam.starwisp.DrawableMap.java

public Marker AddText(final LatLng location, final String text, final int padding, final int fontSize,
        int colour) {
    Marker marker = null;//from  ww  w  .ja  v  a2 s.c  o m

    final TextView textView = new TextView(m_Context);
    textView.setText(text);
    textView.setTextSize(fontSize);
    textView.setTypeface(m_Context.m_Typeface);

    final Paint paintText = textView.getPaint();

    final Rect boundsText = new Rect();
    paintText.getTextBounds(text, 0, textView.length(), boundsText);
    paintText.setTextAlign(Paint.Align.CENTER);

    final Bitmap.Config conf = Bitmap.Config.ARGB_8888;
    final Bitmap bmpText = Bitmap.createBitmap(boundsText.width() + 2 * padding,
            boundsText.height() + 2 * padding, conf);

    final Canvas canvasText = new Canvas(bmpText);
    paintText.setColor(Color.BLACK);

    canvasText.drawText(text, (canvasText.getWidth() / 2) + 3,
            (canvasText.getHeight() - padding - boundsText.bottom) + 3, paintText);

    paintText.setColor(colour);

    canvasText.drawText(text, canvasText.getWidth() / 2, canvasText.getHeight() - padding - boundsText.bottom,
            paintText);

    final MarkerOptions markerOptions = new MarkerOptions().position(location)
            .icon(BitmapDescriptorFactory.fromBitmap(bmpText)).anchor(0.5f, 1);

    marker = map.addMarker(markerOptions);

    return marker;
}