Example usage for android.graphics.drawable Drawable draw

List of usage examples for android.graphics.drawable Drawable draw

Introduction

In this page you can find the example usage for android.graphics.drawable Drawable draw.

Prototype

public abstract void draw(@NonNull Canvas canvas);

Source Link

Document

Draw in its bounds (set via setBounds) respecting optional effects such as alpha (set via setAlpha) and color filter (set via setColorFilter).

Usage

From source file:ru.jango.j0widget.imagebrowser.ImageBrowserView.java

private Bitmap drawableToBitmap(Drawable drawable) {
    if (drawable instanceof BitmapDrawable)
        return ((BitmapDrawable) drawable).getBitmap();

    int width = drawable.getIntrinsicWidth();
    width = width > 0 ? width : 1;/*from ww  w.j a v  a  2s .  c  o m*/
    int height = drawable.getIntrinsicHeight();
    height = height > 0 ? height : 1;

    final Bitmap bitmap = Bitmap.createBitmap(width, height, 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.polyvi.xface.extension.XAppExt.java

private String drawableToBase64(Drawable drawable) {
    int width = drawable.getIntrinsicWidth();
    int height = drawable.getIntrinsicHeight();
    Bitmap bitmap = Bitmap.createBitmap(width, height,
            drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, width, height);
    drawable.draw(canvas);
    String result = null;//from   w w  w . ja  va 2 s.  c om
    ByteArrayOutputStream baos = null;
    try {
        if (bitmap != null) {
            baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            baos.flush();
            baos.close();
            byte[] bitmapBytes = baos.toByteArray();
            result = XBase64.encodeToString(bitmapBytes, Base64.DEFAULT);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (baos != null) {
                baos.flush();
                baos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return result;
}

From source file:fr.simon.marquis.secretcodes.util.ExportContentProvider.java

private void saveImageFiles(ArrayList<SecretCode> secretCodes) {
    for (SecretCode secretCode : secretCodes) {
        try {//  w w w. j a v  a 2 s  .  c o m
            if (secretCode.getDrawableResource() == 0) {
                continue;
            }
            Drawable drawable = getContext().getPackageManager().getDrawable(secretCode.getPackageManager(),
                    secretCode.getDrawableResource(), null);
            if (drawable == null) {
                continue;
            }
            int height = drawable.getIntrinsicHeight();
            int width = drawable.getIntrinsicWidth();
            Bitmap createBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            if (createBitmap == null) {
                continue;
            }
            Canvas canvas = new Canvas(createBitmap);
            drawable.setBounds(0, 0, width, height);
            drawable.draw(canvas);

            FileOutputStream openFileOutput = getContext().openFileOutput(secretCode.getCode() + ".png",
                    Context.MODE_PRIVATE);
            createBitmap.compress(Bitmap.CompressFormat.PNG, 100, openFileOutput);
            openFileOutput.flush();
            openFileOutput.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:org.gateshipone.odyssey.playbackservice.managers.OdysseyNotificationManager.java

public void updateNotification(TrackModel track, PlaybackService.PLAYSTATE state,
        MediaSessionCompat.Token mediaSessionToken) {
    if (track != null) {
        mNotificationBuilder = new NotificationCompat.Builder(mContext);

        // Open application intent
        Intent contentIntent = new Intent(mContext, OdysseyMainActivity.class);
        contentIntent.putExtra(OdysseyMainActivity.MAINACTIVITY_INTENT_EXTRA_REQUESTEDVIEW,
                OdysseyMainActivity.MAINACTIVITY_INTENT_EXTRA_REQUESTEDVIEW_NOWPLAYINGVIEW);
        contentIntent.addFlags(//from  ww  w. j a va 2  s. co m
                Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK
                        | Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_NO_HISTORY);
        PendingIntent contentPendingIntent = PendingIntent.getActivity(mContext, NOTIFICATION_INTENT_OPENGUI,
                contentIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mNotificationBuilder.setContentIntent(contentPendingIntent);

        // Set pendingintents
        // Previous song action
        Intent prevIntent = new Intent(PlaybackService.ACTION_PREVIOUS);
        PendingIntent prevPendingIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_PREVIOUS,
                prevIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action prevAction = new NotificationCompat.Action.Builder(
                R.drawable.ic_skip_previous_48dp, "Previous", prevPendingIntent).build();

        // Pause/Play action
        PendingIntent playPauseIntent;
        int playPauseIcon;
        if (state == PlaybackService.PLAYSTATE.PLAYING) {
            Intent pauseIntent = new Intent(PlaybackService.ACTION_PAUSE);
            playPauseIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_PLAYPAUSE, pauseIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            playPauseIcon = R.drawable.ic_pause_48dp;
        } else {
            Intent playIntent = new Intent(PlaybackService.ACTION_PLAY);
            playPauseIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_PLAYPAUSE, playIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            playPauseIcon = R.drawable.ic_play_arrow_48dp;
        }
        NotificationCompat.Action playPauseAction = new NotificationCompat.Action.Builder(playPauseIcon,
                "PlayPause", playPauseIntent).build();

        // Next song action
        Intent nextIntent = new Intent(PlaybackService.ACTION_NEXT);
        PendingIntent nextPendingIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_NEXT,
                nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action nextAction = new NotificationCompat.Action.Builder(
                R.drawable.ic_skip_next_48dp, "Next", nextPendingIntent).build();

        // Quit action
        Intent quitIntent = new Intent(PlaybackService.ACTION_QUIT);
        PendingIntent quitPendingIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_QUIT,
                quitIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mNotificationBuilder.setDeleteIntent(quitPendingIntent);

        mNotificationBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
        mNotificationBuilder.setSmallIcon(R.drawable.odyssey_notification);
        mNotificationBuilder.addAction(prevAction);
        mNotificationBuilder.addAction(playPauseAction);
        mNotificationBuilder.addAction(nextAction);
        NotificationCompat.MediaStyle notificationStyle = new NotificationCompat.MediaStyle();
        notificationStyle.setShowActionsInCompactView(1, 2);
        notificationStyle.setMediaSession(mediaSessionToken);
        mNotificationBuilder.setStyle(notificationStyle);
        mNotificationBuilder.setContentTitle(track.getTrackName());
        mNotificationBuilder.setContentText(track.getTrackArtistName());

        // Remove unnecessary time info
        mNotificationBuilder.setWhen(0);

        // Cover but only if changed
        if (mLastTrack == null || !track.getTrackAlbumKey().equals(mLastTrack.getTrackAlbumKey())) {
            mLastTrack = track;
            mLastBitmap = null;
        }

        // Only set image if an saved one is available
        if (mLastBitmap != null) {
            mNotificationBuilder.setLargeIcon(mLastBitmap);
        } else {
            /**
             * Create a dummy placeholder image for versions greater android 7 because it
             * does not automatically show the application icon anymore in mediastyle notifications.
             */
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Drawable icon = mContext.getDrawable(R.drawable.notification_placeholder_256dp);

                Bitmap iconBitmap = Bitmap.createBitmap(icon.getIntrinsicWidth(), icon.getIntrinsicHeight(),
                        Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(iconBitmap);
                DrawFilter filter = new PaintFlagsDrawFilter(Paint.ANTI_ALIAS_FLAG, 1);

                canvas.setDrawFilter(filter);
                icon.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
                icon.setFilterBitmap(true);

                icon.draw(canvas);
                mNotificationBuilder.setLargeIcon(iconBitmap);

            } else {
                /**
                 * For older android versions set the null icon which will result in a dummy icon
                 * generated from the application icon.
                 */
                mNotificationBuilder.setLargeIcon(null);

            }
        }

        // Build the notification
        mNotification = mNotificationBuilder.build();

        // Check if run from service and check if playing or pause.
        // Pause notification should be dismissible.
        if (mContext instanceof Service) {
            if (state == PlaybackService.PLAYSTATE.PLAYING) {
                ((Service) mContext).startForeground(NOTIFICATION_ID, mNotification);
            } else {
                ((Service) mContext).stopForeground(false);
            }
        }

        // Send the notification away
        mNotificationManager.notify(NOTIFICATION_ID, mNotification);
    }

}

From source file:com.cyou.cma.clockscreen.widget.LinePageIndicator.java

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    if (mViewPager == null) {
        return;//from w  w  w  .j  ava 2 s . c  o m
    }
    final int count = mViewPager.getAdapter().getCount();
    if (count == 0) {
        return;
    }

    if (mCurrentPage >= count) {
        setCurrentItem(count - 1);
        return;
    }

    final float lineWidthAndGap = mDrawableSelected.getIntrinsicWidth() + mGapWidth;
    final float indicatorWidth = (count * lineWidthAndGap) - mGapWidth;
    final float paddingLeft = getPaddingLeft();
    final float paddingRight = getPaddingRight();

    float horizontalOffset = paddingLeft;
    if (mCentered) {
        horizontalOffset += (getWidth() / 2.0f - indicatorWidth / 2.0f);
    }

    // Draw stroked circles
    for (int i = 0; i < count; i++) {
        Drawable drawable = null;
        if (i == mCurrentPage) {
            drawable = getResources().getDrawable(R.drawable.indicator_selected);

        } else {
            drawable = getResources().getDrawable(R.drawable.indicator_normal);
        }
        final int right = (int) horizontalOffset + drawable.getIntrinsicWidth();
        drawable.setBounds((int) horizontalOffset, 0, right, drawable.getIntrinsicHeight());
        horizontalOffset += drawable.getIntrinsicWidth() + mGapWidth;
        ;
        drawable.draw(canvas);
    }
}

From source file:com.android.leanlauncher.IconCache.java

private Bitmap makeDefaultIcon(UserHandleCompat user) {
    Drawable unbadged = getFullResDefaultActivityIcon();
    Drawable d = mUserManager.getBadgedDrawableForUser(unbadged, user);
    Bitmap b = Bitmap.createBitmap(Math.max(d.getIntrinsicWidth(), 1), Math.max(d.getIntrinsicHeight(), 1),
            Bitmap.Config.ARGB_8888);// w  w  w .  ja  v a  2 s .com
    Canvas c = new Canvas(b);
    d.setBounds(0, 0, b.getWidth(), b.getHeight());
    d.draw(c);
    c.setBitmap(null);
    return b;
}

From source file:io.selendroid.server.model.DefaultSelendroidDriver.java

@Override
@SuppressWarnings("deprecation")
public byte[] takeScreenshot() {
    ViewHierarchyAnalyzer viewAnalyzer = ViewHierarchyAnalyzer.getDefaultInstance();

    // TODO ddary review later, but with getRecentDecorView() it seems to work better
    // long drawingTime = 0;
    // View container = null;
    // for (View view : viewAnalyzer.getTopLevelViews()) {
    // if (view != null && view.isShown() && view.hasWindowFocus()
    // && view.getDrawingTime() > drawingTime) {
    // container = view;
    // drawingTime = view.getDrawingTime();
    // }/*from  w  ww .  j a  v  a 2 s.c o  m*/
    // }
    // final View mainView = container;
    final View mainView = viewAnalyzer.getRecentDecorView();
    if (mainView == null) {
        throw new SelendroidException("No open windows.");
    }
    done = false;
    long end = System.currentTimeMillis() + serverInstrumentation.getAndroidWait().getTimeoutInMillis();
    final byte[][] rawPng = new byte[1][1];
    ServerInstrumentation.getInstance().getCurrentActivity().runOnUiThread(new Runnable() {
        public void run() {
            synchronized (syncObject) {
                Display display = serverInstrumentation.getCurrentActivity().getWindowManager()
                        .getDefaultDisplay();
                Point size = new Point();
                try {
                    display.getSize(size);
                } catch (NoSuchMethodError ignore) { // Older than api level 13
                    size.x = display.getWidth();
                    size.y = display.getHeight();
                }

                // Get root view
                View view = mainView.getRootView();

                // Create the bitmap to use to draw the screenshot
                final Bitmap bitmap = Bitmap.createBitmap(size.x, size.y, Bitmap.Config.ARGB_8888);
                final Canvas canvas = new Canvas(bitmap);

                // Get current theme to know which background to use
                final Activity activity = serverInstrumentation.getCurrentActivity();
                final Theme theme = activity.getTheme();
                final TypedArray ta = theme
                        .obtainStyledAttributes(new int[] { android.R.attr.windowBackground });
                final int res = ta.getResourceId(0, 0);
                final Drawable background = activity.getResources().getDrawable(res);

                // Draw background
                background.draw(canvas);

                // Draw views
                view.draw(canvas);

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                if (!bitmap.compress(Bitmap.CompressFormat.PNG, 70, stream)) {
                    throw new RuntimeException("Error while compressing screenshot image.");
                }
                try {
                    stream.flush();
                    stream.close();
                } catch (IOException e) {
                    throw new RuntimeException("I/O Error while capturing screenshot: " + e.getMessage());
                } finally {
                    Closeable closeable = (Closeable) stream;
                    try {
                        if (closeable != null) {
                            closeable.close();
                        }
                    } catch (IOException ioe) {
                        // ignore
                    }
                }
                rawPng[0] = stream.toByteArray();
                mainView.destroyDrawingCache();
                done = true;
                syncObject.notify();
            }
        }
    });

    waitForDone(end, serverInstrumentation.getAndroidWait().getTimeoutInMillis(), "Failed to take screenshot.");
    return rawPng[0];
}

From source file:ir.besteveryeverapp.ui.Cells.DrawerProfileCell.java

@Override
protected void onDraw(Canvas canvas) {
    int pic = SkinMan.currentSkin.actionPicture();
    Drawable backgroundDrawable = pic != 0 ? ContextCompat.getDrawable(getContext(), pic)
            : ApplicationLoader.getCachedWallpaper();
    int color = ApplicationLoader.getServiceMessageColor();
    if (currentColor != color) {
        currentColor = color;//from w ww.ja  v  a 2s. c om
        shadowView.getDrawable()
                .setColorFilter(new PorterDuffColorFilter(color | 0xff000000, PorterDuff.Mode.MULTIPLY));
    }

    if (ApplicationLoader.isCustomTheme() || pic != 0 && backgroundDrawable != null) {
        phoneTextView.setTextColor(0xffffffff);
        shadowView.setVisibility(VISIBLE);
        if (backgroundDrawable instanceof ColorDrawable) {
            backgroundDrawable.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
            backgroundDrawable.draw(canvas);
        } else if (backgroundDrawable instanceof BitmapDrawable) {
            Bitmap bitmap = ((BitmapDrawable) backgroundDrawable).getBitmap();
            float scaleX = (float) getMeasuredWidth() / (float) bitmap.getWidth();
            float scaleY = (float) getMeasuredHeight() / (float) bitmap.getHeight();
            float scale = scaleX < scaleY ? scaleY : scaleX;
            int width = (int) (getMeasuredWidth() / scale);
            int height = (int) (getMeasuredHeight() / scale);
            int x = (bitmap.getWidth() - width) / 2;
            int y = (bitmap.getHeight() - height) / 2;
            srcRect.set(x, y, x + width, y + height);
            destRect.set(0, 0, getMeasuredWidth(), getMeasuredHeight());
            canvas.drawBitmap(bitmap, srcRect, destRect, paint);
        }
    } else {
        shadowView.setVisibility(INVISIBLE);
        phoneTextView.setTextColor(0xffc2e5ff);
        super.onDraw(canvas);
    }
}

From source file:org.addhen.smssync.presentation.view.ui.fragment.ListWebServiceFragment.java

private void drawSwipeListItemBackground(Canvas c, int dX, View itemView, int actionState) {
    if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
        // Fade out the view as it is swiped out of the parent's bounds
        final float alpha = 2.0f - Math.abs(dX) / (float) itemView.getWidth();
        ViewHelper.setAlpha(itemView, alpha);
        ViewHelper.setTranslationX(itemView, dX);

        Drawable d;
        // Swiping right
        if (dX > 0) {
            d = ContextCompat.getDrawable(getAppContext(), R.drawable.swipe_right_publish_list_item_background);
            d.setBounds(itemView.getLeft(), itemView.getTop(), dX, itemView.getBottom());
        } else { // Swiping left
            d = ContextCompat.getDrawable(getAppContext(), R.drawable.swipe_left_publish_list_item_background);
            d.setBounds(itemView.getRight() + dX, itemView.getTop(), itemView.getRight(), itemView.getBottom());
        }//from   ww  w .  ja v a 2  s .  c o m
        d.draw(c);
    }
}

From source file:com.kmagic.solitaire.DrawMaster.java

/**
 * Create a face card bitmap from resources
 * @param r application resources reference
 * @param id drawable resource id (R.drawable.id)
 * @param width width of the bitmap//w  w w  .j a v a  2 s .com
 * @param height height of the bitmap
 * @return bitmap of the face card resource
 */
private Bitmap createFaceBitmap(final Resources r, final int id, final int width, final int height) {
    Drawable drawable = ResourcesCompat.getDrawable(r, id, null);
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, width, height);
    drawable.draw(canvas);
    return (bitmap);
}