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:Main.java

public static Bitmap drawTextToBitmap(Context mContext, int resourceId, String mText) {
    try {//from w ww.  j  a va2s .co m
        Resources resources = mContext.getResources();
        float scale = resources.getDisplayMetrics().density;
        Bitmap bitmap = BitmapFactory.decodeResource(resources, resourceId);

        android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
        // set default bitmap config if none
        if (bitmapConfig == null) {
            bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
        }
        // resource bitmaps are imutable,
        // so we need to convert it to mutable one
        bitmap = bitmap.copy(bitmapConfig, true);

        Canvas canvas = new Canvas(bitmap);
        // new antialised Paint
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        // text color - #3D3D3D
        paint.setColor(Color.rgb(77, 77, 77));
        // text size in pixels
        paint.setTextSize((int) (13 * scale));
        // text shadow
        paint.setShadowLayer(1f, 0f, 1f, Color.DKGRAY);

        // draw text to the Canvas center
        Rect bounds = new Rect();
        paint.getTextBounds(mText, 0, mText.length(), bounds);
        int x = (int) ((bitmap.getWidth() - bounds.width()) / 4);
        int y = (int) ((bitmap.getHeight() + bounds.height()) / 4);

        canvas.drawText(mText, x * scale, y * scale, paint);

        return bitmap;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;

}

From source file:com.cooltechworks.views.ScratchTextView.java

private static int[] getTextDimens(String text, Paint paint) {

    int end = text.length();
    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, end, bounds);
    int width = bounds.left + bounds.width();
    int height = bounds.bottom + bounds.height();

    return new int[] { width, height };
}

From source file:Main.java

public static Bitmap drawTextToBitmap(Context gContext, String gText, int frontColor, int backColor) {
    Resources resources = gContext.getResources();
    float scale = resources.getDisplayMetrics().density;
    int w = 1536, h = 1280;
    Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
    Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
    android.graphics.Bitmap.Config bitmapConfig = bmp.getConfig();
    Canvas canvas = new Canvas(bmp);

    // new antialised Paint
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    // text color - #3D3D3D
    paint.setColor(frontColor);//  w w w .  ja  v a2 s  .  c o m
    // text size in pixels
    paint.setTextSize((int) (400 * scale));
    // text shadow
    //paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);

    // draw text to the Canvas center
    if (backColor != -1) {
        canvas.drawColor(backColor);
    }
    Rect bounds = new Rect();
    paint.getTextBounds(gText, 0, gText.length(), bounds);
    int x = (bmp.getWidth() - bounds.width()) / 2;
    int y = (bmp.getHeight() + bounds.height()) / 2;
    canvas.drawText(gText, x, y, paint);
    return bmp;
}

From source file:com.viewpagerindicator.TabMovablePageIndicator.java

public static int getTextWidth(String str, float fontSize, Typeface typeface) {
    if (str == null || str.equals("")) {
        return 0;
    }//from   ww w . j  a  va2 s . co m
    Paint pFont = new Paint();
    Rect rect = new Rect();
    pFont.setTextSize(fontSize);
    pFont.setTypeface(typeface);
    pFont.getTextBounds(str, 0, str.length(), rect);
    return rect.width();
}

From source file:eu.iescities.pilot.rovereto.roveretoexplorer.map.MapManager.java

private static Bitmap writeOnMarker(Context mContext, int drawableId, String text) {
    float scale = mContext.getResources().getDisplayMetrics().density;

    Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), drawableId)
            .copy(Bitmap.Config.ARGB_8888, true);

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setTextAlign(Align.CENTER);//from  ww w  .  j  a v  a2s.  c  o  m
    paint.setTextSize(scale * 14);
    paint.setAntiAlias(true);
    paint.setARGB(255, 255, 255, 255);

    Canvas canvas = new Canvas(bitmap);
    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, text.length(), bounds);
    float x = bitmap.getWidth() / 2;
    float y = bitmap.getHeight() / 2;
    canvas.drawText(text, x, y, paint);

    return bitmap;
}

From source file:eu.iescities.pilot.rovereto.roveretoexplorer.map.MapManager.java

private static Bitmap writeOnStoryMarker(Context mContext, int drawableId, String text) {
    float scale = mContext.getResources().getDisplayMetrics().density;

    Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), drawableId)
            .copy(Bitmap.Config.ARGB_8888, true);
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setTextAlign(Align.CENTER);//w w  w.  jav  a2 s.  c  om
    paint.setTextSize(scale * 14);
    paint.setAntiAlias(true);
    paint.setARGB(255, 255, 255, 255);

    Canvas canvas = new Canvas(bitmap);
    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, text.length(), bounds);
    float x = bitmap.getWidth() / 2;
    float y = bitmap.getHeight() / 2 - ((paint.descent() + paint.ascent()) / 2);

    canvas.drawText(text, x, y, paint);

    return bitmap;
}

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

private static int getFontSizeAccordingHeight(int height) {
    Paint paint = new Paint();
    Rect bounds = new Rect();

    paint.setTypeface(Typeface.DEFAULT);
    int incr_text_size = 1;
    boolean found_desired_size = false;

    while (!found_desired_size) {

        paint.setTextSize(incr_text_size);
        String text = "SghMNy";
        paint.getTextBounds(text, 0, text.length(), bounds);

        incr_text_size++;/* www. j ava2  s  . co  m*/

        if (height - bounds.height() <= 2) {
            found_desired_size = true;
        }
        Log.d("font size", "incr size:" + incr_text_size);
    }
    return incr_text_size;
}

From source file:eu.trentorise.smartcampus.trentinofamiglia.map.MapManager.java

private static Bitmap writeOnMarker(Context mContext, int drawableId, String text) {
    float scale = mContext.getResources().getDisplayMetrics().density;

    Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), drawableId)
            .copy(Bitmap.Config.ARGB_8888, true);

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setTextAlign(Align.CENTER);// w w  w .  j  a v  a  2s.co  m
    paint.setTextSize(scale * 14);
    paint.setAntiAlias(true);
    paint.setARGB(255, 255, 255, 255);

    Canvas canvas = new Canvas(bitmap);
    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, text.length(), bounds);
    float x = bitmap.getWidth() / 2;
    float y = bitmap.getHeight() / 2 - 5;
    canvas.drawText(text, x, y, paint);

    return bitmap;
}

From source file:com.fastbootmobile.encore.utils.Utils.java

/**
 * Calculates the optimal size of the text based on the text view width
 *
 * @param textView     The text view in which the text should fit
 * @param desiredWidth The desired final text width, or -1 for the TextView's getMeasuredWidth
 *///from ww w .jav  a  2s . c o  m
public static void adjustTextSize(TextView textView, int desiredWidth) {
    if (desiredWidth <= 0) {
        desiredWidth = textView.getMeasuredWidth();

        if (desiredWidth <= 0) {
            // Invalid width, don't do anything
            Log.w("Utils", "adjustTextSize: Not doing anything (measured width invalid)");
            return;
        }
    }

    // Add some margin to width
    desiredWidth *= 0.8f;

    Paint paint = new Paint();
    Rect bounds = new Rect();

    paint.setTypeface(textView.getTypeface());
    float textSize = textView.getTextSize() * 2.0f;
    paint.setTextSize(textSize);
    String text = textView.getText().toString();
    paint.getTextBounds(text, 0, text.length(), bounds);

    while (bounds.width() > desiredWidth) {
        textSize--;
        paint.setTextSize(textSize);
        paint.getTextBounds(text, 0, text.length(), bounds);
    }

    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
}

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

/**
 * Build a message notification./*from w  w w  .j a v  a2 s. c o  m*/
 * @param context the context
 * @param from the sender
 * @param matrixId the user account id;
 * @param displayMatrixId true to display the matrix id
 * @param largeIcon the notification icon
 * @param unseenNotifiedRoomsCount the number of notified rooms
 * @param body the message body
 * @param roomId the room id
 * @param roomName the room name
 * @param shouldPlaySound true when the notification as sound.
 * @param isInvitationEvent true if it is an invitation notification
 * @return the notification
 */
public static Notification buildMessageNotification(Context context, String from, String matrixId,
        boolean displayMatrixId, Bitmap largeIcon, int unseenNotifiedRoomsCount, String body, String roomId,
        String roomName, boolean shouldPlaySound, boolean isInvitationEvent) {

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setWhen(System.currentTimeMillis());

    if (!TextUtils.isEmpty(from)) {
        // don't display the room name for 1:1 room notifications.
        if (!TextUtils.isEmpty(roomName) && !roomName.equals(from)) {
            builder.setContentTitle(from + " (" + roomName + ")");
        } else {
            builder.setContentTitle(from);
        }
    } else {
        builder.setContentTitle(roomName);
    }

    builder.setContentText(body);
    builder.setAutoCancel(true);
    builder.setSmallIcon(R.drawable.message_notification_transparent);

    if (null != largeIcon) {
        largeIcon = createSquareBitmap(largeIcon);

        // add a bubble in the top right
        if (0 != unseenNotifiedRoomsCount) {
            try {
                android.graphics.Bitmap.Config bitmapConfig = largeIcon.getConfig();

                // set default bitmap config if none
                if (bitmapConfig == null) {
                    bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
                }

                // setLargeIcon must used a 64 * 64 pixels bitmap
                // rescale to have the same text UI.
                float densityScale = context.getResources().getDisplayMetrics().density;
                int side = (int) (64 * densityScale);

                Bitmap bitmapCopy = Bitmap.createBitmap(side, side, bitmapConfig);
                Canvas canvas = new Canvas(bitmapCopy);

                // resize the bitmap to fill in size
                int bitmapWidth = largeIcon.getWidth();
                int bitmapHeight = largeIcon.getHeight();

                float scale = Math.min((float) canvas.getWidth() / (float) bitmapWidth,
                        (float) canvas.getHeight() / (float) bitmapHeight);

                int scaledWidth = (int) (bitmapWidth * scale);
                int scaledHeight = (int) (bitmapHeight * scale);

                Bitmap rescaledBitmap = Bitmap.createScaledBitmap(largeIcon, scaledWidth, scaledHeight, true);
                canvas.drawBitmap(rescaledBitmap, (side - scaledWidth) / 2, (side - scaledHeight) / 2, null);

                String text = "" + unseenNotifiedRoomsCount;

                // prepare the text drawing
                Paint textPaint = new Paint();
                textPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
                textPaint.setColor(Color.WHITE);
                textPaint.setTextSize(10 * densityScale);

                // get its size
                Rect textBounds = new Rect();

                if (-1 == mUnreadBubbleWidth) {
                    textPaint.getTextBounds("99", 0, 2, textBounds);
                    mUnreadBubbleWidth = textBounds.width();
                }

                textPaint.getTextBounds(text, 0, text.length(), textBounds);

                // draw a red circle
                int radius = mUnreadBubbleWidth;
                Paint paint = new Paint();
                paint.setStyle(Paint.Style.FILL);
                paint.setColor(Color.RED);
                canvas.drawCircle(canvas.getWidth() - radius, radius, radius, paint);

                // draw the text
                canvas.drawText(text,
                        canvas.getWidth() - textBounds.width() - (radius - (textBounds.width() / 2)),
                        -textBounds.top + (radius - (-textBounds.top / 2)), textPaint);

                // get the new bitmap
                largeIcon = bitmapCopy;
            } catch (Exception e) {
                Log.e(LOG_TAG, "## buildMessageNotification(): Exception Msg=" + e.getMessage());
            }
        }

        builder.setLargeIcon(largeIcon);
    }

    String name = ": ";
    if (!TextUtils.isEmpty(roomName)) {
        name = " (" + roomName + "): ";
    }

    if (displayMatrixId) {
        from = "[" + matrixId + "]\n" + from;
    }

    builder.setTicker(from + name + body);

    TaskStackBuilder stackBuilder;
    Intent intent;

    intent = new Intent(context, VectorRoomActivity.class);
    intent.putExtra(VectorRoomActivity.EXTRA_ROOM_ID, roomId);

    if (null != matrixId) {
        intent.putExtra(VectorRoomActivity.EXTRA_MATRIX_ID, matrixId);
    }

    stackBuilder = TaskStackBuilder.create(context).addParentStack(VectorRoomActivity.class)
            .addNextIntent(intent);

    // android 4.3 issue
    // use a generator for the private requestCode.
    // When using 0, the intent is not created/launched when the user taps on the notification.
    //
    PendingIntent pendingIntent = stackBuilder.getPendingIntent((new Random()).nextInt(1000),
            PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendingIntent);

    // display the message with more than 1 lines when the device supports it
    NotificationCompat.BigTextStyle textStyle = new NotificationCompat.BigTextStyle();
    textStyle.bigText(from + ":" + body);
    builder.setStyle(textStyle);

    // do not offer to quick respond if the user did not dismiss the previous one
    if (!LockScreenActivity.isDisplayingALockScreenActivity()) {
        if (!isInvitationEvent) {
            // offer to type a quick answer (i.e. without launching the application)
            Intent quickReplyIntent = new Intent(context, LockScreenActivity.class);
            quickReplyIntent.putExtra(LockScreenActivity.EXTRA_ROOM_ID, roomId);
            quickReplyIntent.putExtra(LockScreenActivity.EXTRA_SENDER_NAME, from);
            quickReplyIntent.putExtra(LockScreenActivity.EXTRA_MESSAGE_BODY, body);

            if (null != matrixId) {
                quickReplyIntent.putExtra(LockScreenActivity.EXTRA_MATRIX_ID, matrixId);
            }

            // the action must be unique else the parameters are ignored
            quickReplyIntent.setAction(QUICK_LAUNCH_ACTION + ((int) (System.currentTimeMillis())));
            PendingIntent pIntent = PendingIntent.getActivity(context, 0, quickReplyIntent, 0);
            builder.addAction(R.drawable.vector_notification_quick_reply,
                    context.getString(R.string.action_quick_reply), pIntent);
        } else {
            {
                // offer to type a quick reject button
                Intent leaveIntent = new Intent(context, JoinScreenActivity.class);
                leaveIntent.putExtra(JoinScreenActivity.EXTRA_ROOM_ID, roomId);
                leaveIntent.putExtra(JoinScreenActivity.EXTRA_MATRIX_ID, matrixId);
                leaveIntent.putExtra(JoinScreenActivity.EXTRA_REJECT, true);

                // the action must be unique else the parameters are ignored
                leaveIntent.setAction(QUICK_LAUNCH_ACTION + ((int) (System.currentTimeMillis())));
                PendingIntent pIntent = PendingIntent.getActivity(context, 0, leaveIntent, 0);
                builder.addAction(R.drawable.vector_notification_reject_invitation,
                        context.getString(R.string.reject), pIntent);
            }

            {
                // offer to type a quick accept button
                Intent acceptIntent = new Intent(context, JoinScreenActivity.class);
                acceptIntent.putExtra(JoinScreenActivity.EXTRA_ROOM_ID, roomId);
                acceptIntent.putExtra(JoinScreenActivity.EXTRA_MATRIX_ID, matrixId);
                acceptIntent.putExtra(JoinScreenActivity.EXTRA_JOIN, true);

                // the action must be unique else the parameters are ignored
                acceptIntent.setAction(QUICK_LAUNCH_ACTION + ((int) (System.currentTimeMillis())));
                PendingIntent pIntent = PendingIntent.getActivity(context, 0, acceptIntent, 0);
                builder.addAction(R.drawable.vector_notification_accept_invitation,
                        context.getString(R.string.join), pIntent);
            }
        }

        // Build the pending intent for when the notification is clicked
        Intent roomIntentTap;
        if (isInvitationEvent) {
            // for invitation the room preview must be displayed
            roomIntentTap = CommonActivityUtils.buildIntentPreviewRoom(matrixId, roomId, context,
                    VectorFakeRoomPreviewActivity.class);
        } else {
            roomIntentTap = new Intent(context, VectorRoomActivity.class);
            roomIntentTap.putExtra(VectorRoomActivity.EXTRA_ROOM_ID, roomId);
        }
        // the action must be unique else the parameters are ignored
        roomIntentTap.setAction(TAP_TO_VIEW_ACTION + ((int) (System.currentTimeMillis())));

        // Recreate the back stack
        TaskStackBuilder stackBuilderTap = TaskStackBuilder.create(context)
                .addParentStack(VectorRoomActivity.class).addNextIntent(roomIntentTap);

        builder.addAction(R.drawable.vector_notification_open, context.getString(R.string.action_open),
                stackBuilderTap.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));
    }

    //extendForCar(context, builder, roomId, roomName, from, body);

    Notification n = builder.build();
    n.flags |= Notification.FLAG_SHOW_LIGHTS;
    n.defaults |= Notification.DEFAULT_LIGHTS;

    if (shouldPlaySound) {
        n.defaults |= Notification.DEFAULT_SOUND;
    }

    if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        // some devices crash if this field is not set
        // even if it is deprecated

        // setLatestEventInfo() is deprecated on Android M, so we try to use
        // reflection at runtime, to avoid compiler error: "Cannot resolve method.."
        try {
            Method deprecatedMethod = n.getClass().getMethod("setLatestEventInfo", Context.class,
                    CharSequence.class, CharSequence.class, PendingIntent.class);
            deprecatedMethod.invoke(n, context, from, body, pendingIntent);
        } catch (Exception ex) {
            Log.e(LOG_TAG,
                    "## buildMessageNotification(): Exception - setLatestEventInfo() Msg=" + ex.getMessage());
        }
    }

    return n;
}