Example usage for android.graphics Paint setTextSize

List of usage examples for android.graphics Paint setTextSize

Introduction

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

Prototype

public void setTextSize(float textSize) 

Source Link

Document

Set the paint's text size.

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.//from  w w  w .j  a  v  a2  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:im.neon.util.NotificationUtils.java

/**
 * Build a message notification./*from  w w w.jav  a2 s.  c  om*/
 * @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;
}

From source file:de.mrapp.android.util.BitmapUtil.java

/**
 * Creates and returns a bitmap from a specific text. The text is centered.
 *
 * @param context// w  w w .  j  a v a  2  s.  c  om
 *         The context, which should be used, as an instance of the class {@link Context}. The
 *         context may not be null
 * @param width
 *         The width of the bitmap, which should be created, in pixels as an {@link Integer}
 *         value
 * @param height
 *         The height of the bitmap, which should be created, in pixels as an {@link Integer}
 *         value
 * @param backgroundColor
 *         The background color of the bitmap, which should be created, as an {@link Integer}
 *         value
 * @param text
 *         The text, the bitmap should be created from, as an instance of the type {@link
 *         CharSequence}. The text may neither be null, nor empty
 * @param textSize
 *         The text size, which should be used, in sp as an {@link Integer} value
 * @param textColor
 *         The text color, which should be used, as an {@link Integer} value The color of the
 *         text
 * @param typeface
 *         The typeface, which should be used, as a value of the enum {@link Typeface} or null,
 *         if the default typeface should be used
 * @return The bitmap, which has been created, as an instance of the class {@link Bitmap}
 */
public static Bitmap textToBitmap(@NonNull final Context context, final int width, final int height,
        @ColorInt final int backgroundColor, @NonNull final CharSequence text, final float textSize,
        @ColorInt final int textColor, @Nullable final Typeface typeface) {
    ensureNotNull(context, "The context may not be null");
    ensureNotNull(text, "The text may not be null");
    ensureNotEmpty(text, "The text may not be empty");
    ensureAtLeast(textSize, 1, "The text size must be at least 1");
    Bitmap bitmap = colorToBitmap(width, height, backgroundColor);
    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(textColor);
    paint.setTextSize(textSize * getDensity(context));
    paint.setTextAlign(Align.CENTER);

    if (typeface != null) {
        paint.setTypeface(typeface);
    }

    int x = bitmap.getWidth() / 2;
    int y = (int) ((bitmap.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 2));
    canvas.drawText(text.toString(), 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   www .  j a  va 2  s  . co  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:com.android.mail.text.FolderSpan.java

private int getWidth(Paint p) {
    p.setTextSize(mRes.folderFontSize);
    return Math.min((int) p.measureText(mName) + 2 * mRes.folderHorizontalPadding, mDim.getMaxChipWidth());
}

From source file:com.android.mail.text.FolderSpan.java

private int getHeight(Paint p) {
    p.setTextSize(mRes.folderFontSize);
    final Paint.FontMetricsInt fm = p.getFontMetricsInt();
    return fm.bottom - fm.top;
}

From source file:com.atwal.wakeup.battery.util.Utilities.java

/**
 * Calculates the height of a given string at a specific text size.
 *///from w w w  .j av a 2 s. c o  m
public static float calculateTextHeight(float textSizePx) {
    Paint p = new Paint();
    p.setTextSize(textSizePx);
    Paint.FontMetrics fm = p.getFontMetrics();
    return -fm.top + fm.bottom;
}

From source file:com.github.kubatatami.RoundedView.java

private void drawText(Canvas canvas) {
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setTextSize(getResources().getDimension(R.dimen.item_circle_text_size));

    Rect areaRect = new Rect(0, 0, canvas.getWidth(), canvas.getHeight());
    RectF bounds = new RectF(areaRect);

    bounds.right = paint.measureText(text, 0, text.length());
    bounds.bottom = paint.descent() - paint.ascent();
    bounds.left += (areaRect.width() - bounds.right) / 2.0f;
    bounds.top += (areaRect.height() - bounds.bottom) / 2.0f;

    paint.setColor(Color.WHITE);//  ww w.  j  ava2 s . com

    canvas.drawText(text, bounds.left, bounds.top - paint.ascent(), paint);
}

From source file:com.android.deskclock.timer.TimerView.java

/**
 * Measure the text and add a start padding to the view
 * @param textView view to measure and onb to which add start padding
 *//*from  w  w  w .ja va  2  s . co  m*/
private void addStartPadding(TextView textView) {
    final float gapPadding = 0.45f;
    // allDigits will contain ten digits: "0123456789" in the default locale
    String allDigits = String.format(Locale.getDefault(), "%010d", 123456789);
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setTextSize(textView.getTextSize());
    paint.setTypeface(textView.getTypeface());

    float widths[] = new float[allDigits.length()];
    int ll = paint.getTextWidths(allDigits, widths);
    int largest = 0;
    for (int ii = 1; ii < ll; ii++) {
        if (widths[ii] > widths[largest]) {
            largest = ii;
        }
    }
    // Add left padding to the view - Note: layout inherits LTR
    textView.setPadding((int) (gapPadding * widths[largest]), 0, 0, 0);
}

From source file:org.mariotaku.twidere.text.OriginalStatusSpan.java

@Override
public int getSize(final Paint paint, final CharSequence text, final int start, final int end,
        final Paint.FontMetricsInt fm) {
    paint.setTextSize(paint.getTextSize() * 0.8f);
    return (int) paint.measureText(text, start, end) + mPadding * 2;
}