Example usage for android.graphics Canvas drawBitmap

List of usage examples for android.graphics Canvas drawBitmap

Introduction

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

Prototype

public void drawBitmap(@NonNull Bitmap bitmap, @Nullable Rect src, @NonNull Rect dst, @Nullable Paint paint) 

Source Link

Document

Draw the specified bitmap, scaling/translating automatically to fill the destination rectangle.

Usage

From source file:Main.java

public static Bitmap createFramedImage(Drawable imageDrawable, int borderThickness) {
    int size = Math.min(imageDrawable.getMinimumWidth(), imageDrawable.getMinimumHeight());
    Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    RectF outerRect = new RectF(0, 0, size, size);

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(Color.RED);/*from   w ww.  j a v  a2s  . com*/
    canvas.drawRect(outerRect, paint);

    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    imageDrawable.setBounds(0, 0, size, size);

    // Save the layer to apply the paint
    canvas.saveLayer(outerRect, paint, Canvas.ALL_SAVE_FLAG);
    imageDrawable.draw(canvas);
    canvas.restore();

    // FRAMING THE PHOTO
    float border = size / 15f;

    // 1. Create offscreen bitmap link: http://www.youtube.com/watch?feature=player_detailpage&v=jF6Ad4GYjRU#t=1035s
    Bitmap framedOutput = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
    Canvas framedCanvas = new Canvas(framedOutput);
    // End of Step 1

    // Start - TODO IMPORTANT - this section shouldn't be included in the final code
    // It's needed here to differentiate step 2 (red) with the background color of the activity
    // It's should be commented out after the codes includes step 3 onwards
    // Paint squaredPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    // squaredPaint.setColor(Color.BLUE);
    // framedCanvas.drawRoundRect(outerRect, 0f, 0f, squaredPaint);
    // End

    // 2. Draw an opaque rounded rectangle link:
    RectF innerRect = new RectF(border, border, size - border, size - border);

    Paint innerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    innerPaint.setColor(Color.RED);
    //      framedCanvas.drawRoundRect(innerRect, cornerRadius, cornerRadius, outerPaint);
    framedCanvas.drawRect(innerRect, innerPaint);

    // 3. Set the Power Duff mode link:
    Paint outerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    outerPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));

    // 4. Draw a translucent rounded rectangle link:
    outerPaint.setColor(Color.argb(255, 255, 255, 255));
    //      framedCanvas.drawRoundRect(outerRect, cornerRadius, cornerRadius, outerPaint);
    framedCanvas.drawRect(outerRect, outerPaint);

    // 5. Draw the frame on top of original bitmap
    canvas.drawBitmap(framedOutput, 0f, 0f, null);

    return output;
}

From source file:com.android.settings.users.EditUserPhotoController.java

private void onPhotoCropped(final Uri data, final boolean cropped) {
    new AsyncTask<Void, Void, Bitmap>() {
        @Override//w  ww  .j  a  v a 2 s  .com
        protected Bitmap doInBackground(Void... params) {
            if (cropped) {
                InputStream imageStream = null;
                try {
                    imageStream = mContext.getContentResolver().openInputStream(data);
                    return BitmapFactory.decodeStream(imageStream);
                } catch (FileNotFoundException fe) {
                    Log.w(TAG, "Cannot find image file", fe);
                    return null;
                } finally {
                    if (imageStream != null) {
                        try {
                            imageStream.close();
                        } catch (IOException ioe) {
                            Log.w(TAG, "Cannot close image stream", ioe);
                        }
                    }
                }
            } else {
                // Scale and crop to a square aspect ratio
                Bitmap croppedImage = Bitmap.createBitmap(mPhotoSize, mPhotoSize, Config.ARGB_8888);
                Canvas canvas = new Canvas(croppedImage);
                Bitmap fullImage = null;
                try {
                    InputStream imageStream = mContext.getContentResolver().openInputStream(data);
                    fullImage = BitmapFactory.decodeStream(imageStream);
                } catch (FileNotFoundException fe) {
                    return null;
                }
                if (fullImage != null) {
                    final int squareSize = Math.min(fullImage.getWidth(), fullImage.getHeight());
                    final int left = (fullImage.getWidth() - squareSize) / 2;
                    final int top = (fullImage.getHeight() - squareSize) / 2;
                    Rect rectSource = new Rect(left, top, left + squareSize, top + squareSize);
                    Rect rectDest = new Rect(0, 0, mPhotoSize, mPhotoSize);
                    Paint paint = new Paint();
                    canvas.drawBitmap(fullImage, rectSource, rectDest, paint);
                    return croppedImage;
                } else {
                    // Bah! Got nothin.
                    return null;
                }
            }
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                mNewUserPhotoBitmap = bitmap;
                mNewUserPhotoDrawable = CircleFramedDrawable.getInstance(mImageView.getContext(),
                        mNewUserPhotoBitmap);
                mImageView.setImageDrawable(mNewUserPhotoDrawable);
            }
            new File(mContext.getCacheDir(), TAKE_PICTURE_FILE_NAME).delete();
            new File(mContext.getCacheDir(), CROP_PICTURE_FILE_NAME).delete();
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
}

From source file:com.cocosw.accessory.views.layout.CollapsingTitleLayout.java

@Override
public void draw(Canvas canvas) {
    final int saveCount = canvas.save();

    final int toolbarHeight = mToolbar.getHeight();
    canvas.clipRect(0, 0, canvas.getWidth(), interpolate(canvas.getHeight(), toolbarHeight, mScrollOffset));

    // Now call super and let it draw the background, etc
    super.draw(canvas);

    if (mTitleToDraw != null) {
        float x = mTextLeft;
        float y = mTextTop;

        if (!mUseTexture) {
            // If we're not drawing a texture, we need to properly offset the text
            x -= mDrawnTextBounds.left;/*  w ww  .  j a  va  2  s . co m*/
            y -= mDrawnTextBounds.top;
        }

        if (DEBUG_DRAW) {
            // Just a debug tool, which drawn a Magneta rect in the text bounds
            canvas.drawRect(mTextLeft, mTextTop, mTextRight, mTextTop + mDrawnTextBounds.height(),
                    DEBUG_DRAW_PAINT);
        }

        if (mScale != 1f) {
            canvas.scale(mScale, mScale, x, y);
        }

        if (mUseTexture && mExpandedTitleTexture != null) {
            // If we should use a texture, draw it instead of text
            canvas.drawBitmap(mExpandedTitleTexture, x, y, mTexturePaint);
        } else {
            canvas.drawText(mTitleToDraw, x, y, mTextPaint);
        }
    }

    canvas.restoreToCount(saveCount);
}

From source file:com.cosmicsubspace.nerdyaudio.visuals.PlayControlsView.java

@Override
protected void onDraw(Canvas canvas) {

    //Log2.log(2,this,buttonFollower.getInfluence().getValue(),playBtnRestPosition.getInfluence().getValue());

    currentFrameTime = System.currentTimeMillis();

    pt.setColor(menuColor);/*from  w  w  w.j  a  va2s  .c  om*/
    canvas.drawRect(0, h - barHeight.getValue(currentFrameTime).getValue("Height"), w, h, pt);

    titleAnimatable.draw(canvas, pt, currentFrameTime);

    artistAnimatable.draw(canvas, pt, currentFrameTime);

    filePath.draw(canvas, pt, currentFrameTime);
    if (albumArt != null) {
        pt.setAlpha(Math.round(albumArtColor.getValue(currentFrameTime).getValue("alpha")));
        canvas.drawBitmap(albumArt, null, artBoundsAnim.getRectF(currentFrameTime), pt);
        //Log2.log(1,this, "trying to draw..");
        pt.setAlpha(255);
    }

    waveform.draw(canvas, pt, currentFrameTime);

    pt.setColor(Color.argb(50, 0, 0, 0));

    pt.setColor(buttonColor);

    playBtn.draw(canvas, pt, currentFrameTime);

    pauseBtn.draw(canvas, pt, currentFrameTime);

    prevBtn.draw(canvas, pt, currentFrameTime);
    nextBtn.draw(canvas, pt, currentFrameTime);

    if (wf != null && ap != null && wf.isReady() && wf.getFilename().equals(ap.getSourceString())) {
        setCurrentPosition((float) (ap.getMusicCurrentFrame() / (double) wf.getNumOfFrames()));

        if (!dragMode) {
            timestampAnim.setText(wf.frameNumberToTimeStamp(ap.getMusicCurrentFrame()));
        }

        timestampAnim.draw(canvas, pt, currentFrameTime);

        buttonFollowerProgress.getBasis().setValue("X", w * currentPosition);
    }

    invalidate();

}

From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowser.java

private void setButtonImages(View view, BrowserButton buttonProps, int disabledAlpha) {
    Drawable normalDrawable = null;/*www  .  j  a  v  a 2s. c  o m*/
    Drawable disabledDrawable = null;
    Drawable pressedDrawable = null;

    CharSequence description = view.getContentDescription();

    if (buttonProps.image != null || buttonProps.wwwImage != null) {
        try {
            normalDrawable = getImage(buttonProps.image, buttonProps.wwwImage, buttonProps.wwwImageDensity);
            ViewGroup.LayoutParams params = view.getLayoutParams();
            params.width = normalDrawable.getIntrinsicWidth();
            params.height = normalDrawable.getIntrinsicHeight();
        } catch (Resources.NotFoundException e) {
            emitError(ERR_LOADFAIL,
                    String.format("Image for %s, %s, failed to load", description, buttonProps.image));
        } catch (IOException ioe) {
            emitError(ERR_LOADFAIL,
                    String.format("Image for %s, %s, failed to load", description, buttonProps.wwwImage));
        }
    } else {
        emitWarning(WRN_UNDEFINED,
                String.format("Image for %s is not defined. Button will not be shown", description));
    }

    if (buttonProps.imagePressed != null || buttonProps.wwwImagePressed != null) {
        try {
            pressedDrawable = getImage(buttonProps.imagePressed, buttonProps.wwwImagePressed,
                    buttonProps.wwwImageDensity);
        } catch (Resources.NotFoundException e) {
            emitError(ERR_LOADFAIL, String.format("Pressed image for %s, %s, failed to load", description,
                    buttonProps.imagePressed));
        } catch (IOException e) {
            emitError(ERR_LOADFAIL, String.format("Pressed image for %s, %s, failed to load", description,
                    buttonProps.wwwImagePressed));
        }
    } else {
        emitWarning(WRN_UNDEFINED, String.format("Pressed image for %s is not defined.", description));
    }

    if (normalDrawable != null) {
        // Create the disabled state drawable by fading the normal state
        // drawable. Drawable.setAlpha() stopped working above Android 4.4
        // so we gotta bring out some bitmap magic. Credit goes to:
        // http://stackoverflow.com/a/7477572
        Bitmap enabledBitmap = ((BitmapDrawable) normalDrawable).getBitmap();
        Bitmap disabledBitmap = Bitmap.createBitmap(normalDrawable.getIntrinsicWidth(),
                normalDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(disabledBitmap);

        Paint paint = new Paint();
        paint.setAlpha(disabledAlpha);
        canvas.drawBitmap(enabledBitmap, 0, 0, paint);

        Resources activityRes = cordova.getActivity().getResources();
        disabledDrawable = new BitmapDrawable(activityRes, disabledBitmap);
    }

    StateListDrawable states = new StateListDrawable();
    if (pressedDrawable != null) {
        states.addState(new int[] { android.R.attr.state_pressed }, pressedDrawable);
    }
    if (normalDrawable != null) {
        states.addState(new int[] { android.R.attr.state_enabled }, normalDrawable);
    }
    if (disabledDrawable != null) {
        states.addState(new int[] {}, disabledDrawable);
    }

    setBackground(view, states);
}

From source file:com.ameron32.apps.tapnotes._trial.ui.CollapsingTitleLayout.java

@Override
public void draw(Canvas canvas) {
    final int saveCount = canvas.save();

    final int toolbarHeight = mToolbar.getHeight();
    canvas.clipRect(0, 0, canvas.getWidth(), interpolate(canvas.getHeight(), toolbarHeight, mScrollOffset));

    // Now call super and let it draw the background, etc
    super.draw(canvas);

    if (mTitleToDraw != null) {
        float x = mTextLeft;
        float y = mTextTop;

        final float ascent = mTextPaint.ascent() * mScale;
        final float descent = mTextPaint.descent() * mScale;
        final float h = descent - ascent;

        if (DEBUG_DRAW) {
            // Just a debug tool, which drawn a Magneta rect in the text bounds
            canvas.drawRect(mTextLeft, y - h + descent, mTextRight, y + descent, DEBUG_DRAW_PAINT);
        }//from  ww w . j a v a2  s.c o  m

        if (mUseTexture) {
            y = y - h + descent;
        }

        if (mScale != 1f) {
            canvas.scale(mScale, mScale, x, y);
        }

        if (mUseTexture && mExpandedTitleTexture != null) {
            // If we should use a texture, draw it instead of text
            canvas.drawBitmap(mExpandedTitleTexture, x, y, mTexturePaint);
        } else {
            canvas.drawText(mTitleToDraw, x, y, mTextPaint);
        }
    }

    canvas.restoreToCount(saveCount);
}

From source file:Main.java

public static Bitmap createRoundedFramedImage(Drawable imageDrawable, int borderThickness, int color) {
    int size = Math.min(imageDrawable.getMinimumWidth(), imageDrawable.getMinimumHeight());
    //      Drawable imageDrawable = (image != null) ? new BitmapDrawable(image) : placeHolder;

    Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    RectF outerRect = new RectF(0, 0, size, size);
    float cornerRadius = size / 18f;

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(Color.RED);/*from w  w  w . j  ava 2  s  .c  om*/
    canvas.drawRoundRect(outerRect, cornerRadius, cornerRadius, paint);

    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    imageDrawable.setBounds(0, 0, size, size);

    // Save the layer to apply the paint
    canvas.saveLayer(outerRect, paint, Canvas.ALL_SAVE_FLAG);
    imageDrawable.draw(canvas);
    canvas.restore();

    // FRAMING THE PHOTO
    float border = size / 15f;

    // 1. Create offscreen bitmap link: http://www.youtube.com/watch?feature=player_detailpage&v=jF6Ad4GYjRU#t=1035s
    Bitmap framedOutput = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
    Canvas framedCanvas = new Canvas(framedOutput);
    // End of Step 1

    // Start - TODO IMPORTANT - this section shouldn't be included in the final code
    // It's needed here to differentiate step 2 (red) with the background color of the activity
    // It's should be commented out after the codes includes step 3 onwards
    // Paint squaredPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    // squaredPaint.setColor(Color.BLUE);
    // framedCanvas.drawRoundRect(outerRect, 0f, 0f, squaredPaint);
    // End

    // 2. Draw an opaque rounded rectangle link:
    // http://www.youtube.com/watch?feature=player_detailpage&v=jF6Ad4GYjRU#t=1044s
    RectF innerRect = new RectF(border, border, size - border, size - border);

    Paint innerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    innerPaint.setColor(Color.RED);
    framedCanvas.drawRoundRect(innerRect, cornerRadius, cornerRadius, innerPaint);

    // 3. Set the Power Duff mode link:
    // http://www.youtube.com/watch?feature=player_detailpage&v=jF6Ad4GYjRU#t=1056s
    Paint outerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    outerPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));

    // 4. Draw a translucent rounded rectangle link:
    // http://www.youtube.com/watch?feature=player_detailpage&v=jF6Ad4GYjRU
    outerPaint.setColor(color);
    framedCanvas.drawRoundRect(outerRect, cornerRadius, cornerRadius, outerPaint);

    // 5. Draw the frame on top of original bitmap
    canvas.drawBitmap(framedOutput, 0f, 0f, null);

    return output;
}

From source file:Main.java

public static Bitmap createRoundedFramedImage(Drawable imageDrawable, int borderThickness) {
    int size = Math.min(imageDrawable.getMinimumWidth(), imageDrawable.getMinimumHeight());
    //      Drawable imageDrawable = (image != null) ? new BitmapDrawable(image) : placeHolder;

    Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    RectF outerRect = new RectF(0, 0, size, size);
    float cornerRadius = size / 18f;

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(Color.RED);//w  w  w  .j  a v a 2 s.co  m
    canvas.drawRoundRect(outerRect, cornerRadius, cornerRadius, paint);

    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    imageDrawable.setBounds(0, 0, size, size);

    // Save the layer to apply the paint
    canvas.saveLayer(outerRect, paint, Canvas.ALL_SAVE_FLAG);
    imageDrawable.draw(canvas);
    canvas.restore();

    // FRAMING THE PHOTO
    float border = size / 15f;

    // 1. Create offscreen bitmap link: http://www.youtube.com/watch?feature=player_detailpage&v=jF6Ad4GYjRU#t=1035s
    Bitmap framedOutput = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
    Canvas framedCanvas = new Canvas(framedOutput);
    // End of Step 1

    // Start - TODO IMPORTANT - this section shouldn't be included in the final code
    // It's needed here to differentiate step 2 (red) with the background color of the activity
    // It's should be commented out after the codes includes step 3 onwards
    // Paint squaredPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    // squaredPaint.setColor(Color.BLUE);
    // framedCanvas.drawRoundRect(outerRect, 0f, 0f, squaredPaint);
    // End

    // 2. Draw an opaque rounded rectangle link:
    // http://www.youtube.com/watch?feature=player_detailpage&v=jF6Ad4GYjRU#t=1044s
    RectF innerRect = new RectF(border, border, size - border, size - border);

    Paint innerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    innerPaint.setColor(Color.RED);
    framedCanvas.drawRoundRect(innerRect, cornerRadius, cornerRadius, innerPaint);

    // 3. Set the Power Duff mode link:
    // http://www.youtube.com/watch?feature=player_detailpage&v=jF6Ad4GYjRU#t=1056s
    Paint outerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    outerPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));

    // 4. Draw a translucent rounded rectangle link:
    // http://www.youtube.com/watch?feature=player_detailpage&v=jF6Ad4GYjRU
    outerPaint.setColor(Color.argb(100, 0, 0, 0));
    framedCanvas.drawRoundRect(outerRect, cornerRadius, cornerRadius, outerPaint);

    // 5. Draw the frame on top of original bitmap
    canvas.drawBitmap(framedOutput, 0f, 0f, null);

    return output;
}