Android image viewer onDraw bitmap
The android image viewer onDraw bitmap tutorial describes how to display the image bitmap in the custom image view using the onDraw method.
To get the bitmap from the calling activity we will be passing the bitmap’s Uri to the custom image view and then loading it from there.
Once we have the bitmap we will use it’s aspect ratio to work out the dimensions for the bitmap to be displayed.
Get Code
The code can be found on github from the following instructions below
https://github.com/mobapptuts/android_image_viewer.git Tag
image-viewer-setimagebitmap
or you can run this command
git clone https://github.com/mobapptuts/android_image_viewer.git –branch
image-viewer-setimagebitmap
Code Samples
Align the custom view to the center
activity_image_view_main.xml
<mobapptut.com.imageviewer.PinchZoomImageView android:visibility="invisible" android:id="@+id/pinchZoomImageView" android:layout_centerInParent="true" android:layout_width="match_parent" android:layout_height="match_parent" />
Create members for the bitmap, bitmap dimensions & aspect ration
PinchZoomImageView
private Bitmap mBitmap; private int mImageWidth; private int mImageHeight;
Create a method for getting the bitmap from the Uri and the scaling it
PinchZoomImageView
public void setImageUri(Uri uri) { try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), uri); float aspecRatio = (float) bitmap.getHeight() / (float) bitmap.getWidth(); DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); mImageWidth = displayMetrics.widthPixels; mImageHeight = Math.round(mImageWidth * aspecRatio); mBitmap = Bitmap.createScaledBitmap(bitmap, mImageWidth, mImageHeight, false); invalidate(); requestLayout(); } catch (IOException e) { e.printStackTrace(); } }
Draw the bitmap on the canvas
PinchZoomImageView
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.save(); canvas.drawBitmap(mBitmap, 0, 0, null); canvas.restore(); }
Call the setImageUri method from the activity
private void pinchZoomPan() { mPinchZoomImageView.setImageUri(mImageUri); mImageView.setAlpha(0.f); mPinchZoomImageView.setVisibility(View.VISIBLE); }
Android image viewer onDraw bitmap summary
In the android image viewer zoom animation tutorial we passed the Uri to the image file and loaded it into the custom image view.
We then calculated the aspect ration of the bitmap.
And then created a scaled version of the bitmap.
After that we needed to reload the custom image view to display the bitmap in the image view.
Finally we need to draw the bitmap in the custom view’s onDraw method.