Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm having trouble understand what PhotoView's getDisplayRect() actually returns (building android photo cropping tool)

Tags:

java

android

math

I'm trying to use the PhotoView library to build a cropping tool for photos but I'm having trouble understanding the value returned by getDisplayRect(). I set the photo on the ImageView like so:

photo.setImageDrawable(new BitmapDrawable(getResources(), image));

where image is the Bitmap object. I then setup some scaling values:

float minScale = ((float)image.getWidth() > (float)image.getHeight())
    ? (float)image.getWidth() / (float)image.getHeight()
    : (float)image.getHeight() / (float)image.getWidth();
attacher.setMaxScale(minScale * 5f);
attacher.setMidScale(minScale * 2.5f);
attacher.setMinScale(minScale);
attacher.setScale(minScale, (float)image.getWidth() / 2f,(float)image.getHeight() / 2f, false);
attacher.update();

where attacher is the PhotoViewAttacher object.

When the user is done i use the following to determine the portion of the Bitmap that is visible in the ImageView:

RectF rect      = attacher.getDisplayRect();
float scale             = attacher.getScale();
PhotoData ret   = new PhotoData(data);
ret.x       = (int)(Math.abs(rect.left) / scale);
ret.y       = (int)(Math.abs(rect.top) / scale);
ret.width   = (int)(rect.width() / scale);
ret.height  = (int)(rect.height() / scale);

I get unexpected results though. Maybe someone here can provide some insights?

like image 306
Brian Dilley Avatar asked Sep 02 '13 06:09

Brian Dilley


1 Answers

Here's the answer:

            RectF rect          = attacher.getDisplayRect();
            float viewScale     = attacher.getScale();

            float imageRatio = (float)size.width() / (float)size.height();
            float viewRatio = (float)photoView.getWidth() / (float)photoView.getHeight();

            float scale = 0;
            if (imageRatio > viewRatio) {
                // scale is based on image width
                scale = 1 / ((float)size.width() / (float)photoView.getWidth() / viewScale);

            } else {
                // scale is based on image height, or 1
                scale = 1 / ((float)size.height() / (float)photoView.getHeight() / viewScale);
            }

            // translate to bitmap scale
            rect.left       = -rect.left / scale;
            rect.top        = -rect.top / scale;
            rect.right      = rect.left + ((float)photoView.getWidth() / scale);
            rect.bottom     = rect.top + ((float)photoView.getHeight() / scale);

            if (rect.top<0) {
                rect.bottom -= Math.abs(rect.top);
                rect.top = 0;
            }
            if (rect.left<0) {
                rect.right -= Math.abs(rect.left);
                rect.left = 0;
            }
like image 147
Brian Dilley Avatar answered Oct 22 '22 13:10

Brian Dilley