我正在尝试使用 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();
其中 attacher
是 PhotoViewAttacher
对象。
当用户完成后,我使用以下方法确定在 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/