Search code examples
androidimagebitmapzoomingcrop

Crop Bitmap using RectF parameters on Android


Using MikeOrtiz's awesome ImageView implementation with touch and zoom events, I wanted to crop a picture taken with the camera to match the zoom. Using his method...

// Return a Rect representing the zoomed image.
RectF getZoomedRect();

...I tried cropping the resulting picture bitmap to the zoom size like so:

RectF zoomCoordinates = mTouchImageView.getZoomedRect();

Bitmap croppedBitmapToOverview = Bitmap.createBitmap(
                AppResources.sCurrentImage,
                ((int) zoomCoordinates.left),
                ((int) zoomCoordinates.top),
                ((int) zoomCoordinates.width()),
                ((int) zoomCoordinates.height()));

However I get a "must be bigger than 0" error with this. While debugging I noticed ALL values were 0 due to casting to an Integer. The real values however go something like this:

//Log.d print for each of those fields without the int cast
Left 0.34047672
Top 0.20797288
Width 0.33333334
Height 0.3429547

So there's my problem, but I can't see how to fix this. I've never worked with bitmaps before or canvas, Rect, etc.

Is there some tweaking I could do to these values, or should I take a different approach altogether?


Solution

  • Got around the problem by simply taking a "screenshot" of the View of sorts. This got me a Bitmap with the picture as it was zoomed

    mTouchImageView.setDrawingCacheEnabled(true);
            AppResources.sCurrentImage = Bitmap.createBitmap(mTouchImageView.getDrawingCache());