List of usage examples for android.graphics Paint setTypeface
public Typeface setTypeface(Typeface typeface)
From source file:Main.java
public static Bitmap getTextImage(String text, float size, int width, int height) { final Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); final Paint paint = new Paint(); final Canvas canvas = new Canvas(bmp); canvas.drawColor(Color.WHITE); paint.setColor(Color.BLACK);// ww w. j a v a2 s .c o m paint.setStyle(Style.FILL); paint.setAntiAlias(true); paint.setTextAlign(Align.CENTER); paint.setTextSize(size); paint.setTypeface(Typeface.DEFAULT); canvas.drawText(text, width / 2, height / 2, 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; }/* w w w. j av a2s . c om*/ 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: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++;//from w w w.ja va 2 s. c om 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:im.neon.util.NotificationUtils.java
/** * Build a message notification./*from w ww . 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; }
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.kmagic.solitaire.DrawMaster.java
/** * Get paint for text use//from w w w .j a va2 s .c o m * @return red paint object */ public static Paint getTextPaint(final float fontSize, final Paint.Align align) { Paint paint = getPaint(); paint.setTextSize(fontSize); paint.setTypeface(Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD)); paint.setTextAlign(align); return (paint); }
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 *//* w w w . j a va2 s .com*/ 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:org.cocos2dx.lib.Cocos2dxBitmap.java
private static Paint newPaint(String fontName, int fontSize, int alignment) { Paint paint = new Paint(); paint.setColor(Color.WHITE);// ww w. j av a 2 s . c o m paint.setTextSize(fontSize); paint.setAntiAlias(true); /* * Set type face for paint, now it support .ttf file. */ if (fontName.endsWith(".ttf")) { try { //Typeface typeFace = Typeface.createFromAsset(context.getAssets(), fontName); Typeface typeFace = Cocos2dxTypefaces.get(context, fontName); paint.setTypeface(typeFace); } catch (Exception e) { Log.e("Cocos2dxBitmap", "error to create ttf type face: " + fontName); /* * The file may not find, use system font */ paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL)); } } else { paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL)); } int hAlignment = alignment & 0x0F; switch (hAlignment) { case HALIGNCENTER: paint.setTextAlign(Align.CENTER); break; case HALIGNLEFT: paint.setTextAlign(Align.LEFT); break; case HALIGNRIGHT: paint.setTextAlign(Align.RIGHT); break; default: paint.setTextAlign(Align.LEFT); break; } return paint; }
From source file:com.taobao.weex.utils.TypefaceUtil.java
public static void applyFontStyle(Paint paint, int style, int weight, String family) { int oldStyle; Typeface typeface = paint.getTypeface(); if (typeface == null) { oldStyle = 0;/*from w w w .j a v a2 s . c om*/ } else { oldStyle = typeface.getStyle(); } int want = 0; if ((weight == Typeface.BOLD) || ((oldStyle & Typeface.BOLD) != 0 && weight == WXStyle.UNSET)) { want |= Typeface.BOLD; } if ((style == Typeface.ITALIC) || ((oldStyle & Typeface.ITALIC) != 0 && style == WXStyle.UNSET)) { want |= Typeface.ITALIC; } if (family != null) { typeface = getOrCreateTypeface(family, want); } if (typeface != null) { paint.setTypeface(Typeface.create(typeface, want)); } else { paint.setTypeface(Typeface.defaultFromStyle(want)); } }
From source file:de.mrapp.android.util.BitmapUtil.java
/** * Creates and returns a bitmap from a specific text. The text is centered. * * @param context//from ww w . j ava 2 s .c o m * 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; }