java - 我无法理解 PhotoView 的 getDisplayRect() 实际返回的内容(构建 android 照片裁剪工具)

标签 java android math

我正在尝试使用 PhotoView库来构建照片裁剪工具,但我无法理解 getDisplayRect() 返回的值。我像这样在 ImageView 上设置照片:

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

其中 image 是位图对象。然后我设置了一些缩放值:

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();

其中 attacherPhotoViewAttacher 对象。

当用户完成后,我使用以下方法确定在 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);

虽然我得到了意想不到的结果。也许这里有人可以提供一些见解?

最佳答案

答案如下:

            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;
            }

关于java - 我无法理解 PhotoView 的 getDisplayRect() 实际返回的内容(构建 android 照片裁剪工具),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18566737/

相关文章:

android - 插入到sqlite数据库时出现空指针异常 - Android

java - 我只想使用 volley android 将数据插入 mysql 数据库 php

Java Runtime exec 方法在使用自定义 URI 时抛出错误

java - 更改 playn 中的 VECTOR_OUTLINE 颜色

java - 查看解析文件输出的方法?

javascript - 在 Cordova 中加载外部 URL 时为 "net::ERR_CACHE_MISS"

java - 计算不相交的有向字母

Ruby Newton 方法给出了错误的结果?

generics - Kotlin,通用加法

java - 初学者 Java 构造函数中不需要参数错误