Example usage for android.graphics Canvas getWidth

List of usage examples for android.graphics Canvas getWidth

Introduction

In this page you can find the example usage for android.graphics Canvas getWidth.

Prototype

public int getWidth() 

Source Link

Document

Returns the width of the current drawing layer

Usage

From source file:io.jawg.osmcontributor.ui.utils.BitmapHandler.java

public static Bitmap drawableToBitmap(Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable) drawable).getBitmap();
    }/*  w  w  w. ja v a 2s. co  m*/
    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
            Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);
    return bitmap;
}

From source file:com.google.samples.apps.iosched.util.UIUtils.java

public static Bitmap vectorToBitmap(@NonNull Context context, @DrawableRes int drawableResId) {
    VectorDrawableCompat vector = VectorDrawableCompat.create(context.getResources(), drawableResId,
            context.getTheme());//ww w .ja  v a  2 s . c o  m
    final Bitmap bitmap = Bitmap.createBitmap(vector.getIntrinsicWidth(), vector.getIntrinsicHeight(),
            Bitmap.Config.ARGB_8888);
    final Canvas canvas = new Canvas(bitmap);
    vector.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    vector.draw(canvas);
    return bitmap;
}

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

/**
 * Creates and returns a bitmap from a specific drawable.
 *
 * @param drawable/* w w w  .  j  a  v  a2s  .  c o  m*/
 *         The drawable, which should be converted, as an instance of the class {@link
 *         Drawable}. The drawable may not be null
 * @return The bitmap, which has been created, as an instance of the class {@link Bitmap}
 */
public static Bitmap drawableToBitmap(@NonNull final Drawable drawable) {
    ensureNotNull(drawable, "The drawable may not be null");

    if (drawable instanceof BitmapDrawable) {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;

        if (bitmapDrawable.getBitmap() != null) {
            return bitmapDrawable.getBitmap();
        }
    }

    Bitmap bitmap;

    if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
        bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
    } else {
        bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                Bitmap.Config.ARGB_8888);
    }

    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);
    return bitmap;
}

From source file:org.wikipedia.page.shareafact.SnippetImage.java

private static void drawGradient(@NonNull Canvas canvas) {
    // draw a dark gradient over the image, so that the white text
    // will stand out better against it.
    final int gradientStartColor = 0x60000000;
    final int gradientStopColor = 0xA0000000;
    Shader shader = new LinearGradient(0, 0, 0, canvas.getHeight(), gradientStartColor, gradientStopColor,
            Shader.TileMode.CLAMP);//from   w w w . j a va  2  s  . c  o m
    Paint paint = new Paint();
    paint.setShader(shader);
    canvas.drawRect(new Rect(0, 0, canvas.getWidth(), canvas.getHeight()), paint);
}

From source file:uk.org.ngo.squeezer.util.ImageWorker.java

/**
 * Adds a debug swatch to a canvas. The marker is a triangle pointing north-west
 * on the top left corner, the edges are 25% of the canvas' width and height.
 *
 * @param canvas The canvas to draw on./*from   www .  j  av  a  2  s . c o  m*/
 * @param color The colour to use for the swatch.
 */
public static void addDebugSwatch(Canvas canvas, int color) {
    float width = canvas.getWidth();
    float height = canvas.getHeight();

    Path path = new Path();
    path.lineTo(width / 4, 0);
    path.lineTo(0, height / 4);
    path.lineTo(0, 0);

    // Draw the swatch.
    mCacheDebugPaint.setColor(color);
    mCacheDebugPaint.setStyle(Paint.Style.FILL);
    canvas.drawPath(path, mCacheDebugPaint);

    // Stroke the swatch with a white hairline.
    mCacheDebugPaint.setColor(Color.WHITE);
    mCacheDebugPaint.setStyle(Paint.Style.STROKE);
    mCacheDebugPaint.setStrokeWidth(0);
    canvas.drawPath(path, mCacheDebugPaint);
}

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

/**
 * Build a message notification.//from  w  ww.j ava 2s . 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:com.forrestguice.suntimeswidget.SuntimesUtils.java

/**
 * @param context context used to access resources
 * @param drawable a Drawable/*from  w ww .  j a  v  a 2s.  co  m*/
 * @param w width (pixels or dp)
 * @param h height (pixels or dp)
 * @param pxValues true w and h are in pixels, false w and h are in dp
 * @return a Bitmap measuring w,h of the specified drawable
 */
public static Bitmap drawableToBitmap(Context context, Drawable drawable, int w, int h, boolean pxValues) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable) drawable).getBitmap();
    }

    if (!pxValues) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        w = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, w, metrics);
        h = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, h, metrics);
    }
    //Log.d("DEBUG", "drawableToBitmap: " + drawable.toString() + "::" + w + ", " + h);

    if (w <= 0 || h <= 0) {
        Log.w("drawableToBitmap", "invalid width or height: " + w + ", " + h);
        w = h = 1;
    }

    Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);
    return bitmap;
}

From source file:io.jawg.osmcontributor.ui.utils.views.customs.ImageProgressBar.java

@Override
public void draw(Canvas canvas) {
    oval.set(canvas.getWidth() / 2 - radius, canvas.getHeight() / 2 - radius, canvas.getWidth() / 2 + radius,
            canvas.getHeight() / 2 + radius);

    drawCircle(canvas, level, color);//from  ww  w.ja  v a2 s  .  c o m
}

From source file:com.github.topbottomsnackbar.TBSnackbar.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static Bitmap getBitmap(VectorDrawable vectorDrawable) {
    Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(),
            Bitmap.Config.ARGB_8888);/*from   w  w  w .jav  a  2  s. c o m*/
    Canvas canvas = new Canvas(bitmap);
    vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    vectorDrawable.draw(canvas);
    return bitmap;
}

From source file:com.microsoft.mimickeralarm.onboarding.BubblePagerIndicator.java

@Override
protected void onDraw(Canvas canvas) {
    int width = canvas.getWidth();
    int height = canvas.getHeight();
    if (mTotalPositions == 0) {
        return;/*  w w w .  ja v  a 2 s. c  om*/
    }
    mPaint.setAlpha(122);
    float buckets = (float) width / mTotalPositions;
    float radius = Math.min(buckets / 2f, height / 2f);
    for (int i = 0; i < mTotalPositions; i++) {
        canvas.drawCircle(i * buckets + buckets / 2f, height / 2f, radius, mPaint);
    }
    mPaint.setAlpha(255);
    canvas.drawCircle(mPosition * buckets + buckets / 2f, height / 2f, radius, mPaint);
}