缩放矩形以匹配位图

时间:2014-09-26 16:05:56

标签: android image bitmap android-bitmap

我正在尝试裁剪位图。我首先将原始位图向下缩放以适合视图,然后在视图上绘制一个矩形,用户可以移动并缩放以裁剪图像,就像从图库中导入图片时在instagram中可以做的那样。我遇到的问题是缩放矩形以匹配原始位图比例来裁剪。以下是发生的事情:

广场的中间是最终结果应该是

enter image description here

我们实际得到的是: enter image description here

我知道这只是数学,但我昨晚花了好几个小时才想弄清楚..我做错了什么?

Bitmap bmp;


float scalefactor = (float)this.mOriginalBitmap.getWidth() / (float)this.mBmpScaledForView.getWidth();


float dh = (this.mCropBoxRect.right - this.mCropBoxRect.left) * (scalefactor-1f);
float dv = (this.mCropBoxRect.bottom - this.mCropBoxRect.top) * (scalefactor-1f);

float l = (float)this.mCropBoxRect.left + dh/2f;
float r = (float)this.mCropBoxRect.right + dh/2f;

float t = (float)this.mCropBoxRect.top + dv/2f;
float b = (float)this.mCropBoxRect.bottom + dv/2f;

RectF scaleRec = new RectF(l, t, r, b);

bmp = Bitmap.createBitmap(this.mOriginalBitmap, (int)scaleRec.left, (int)scaleRec.top, (int)scaleRec.width(), (int)scaleRec.height());

bmp = Bitmap.createScaledBitmap(bmp, MyConsts.outputSize, MyConsts.outputSize, false);

1 个答案:

答案 0 :(得分:2)

我能够通过使用矩阵使其工作。答案非常简单,只是到达那里对我来说很困难。

Bitmap bmp;

//Get the scale factors for both vertical and horizontal since we're dealing with a square inside of a rectangle 
float scalefactorH = (float)mOriginalBitmap.getWidth() / (float)mBmpScaledForView.getWidth();
float scalefactorV = (float)mOriginalBitmap.getHeight() / (float)mBmpScaledForView.getHeight();

//Create a matrix and apply the scale factors
Matrix m = new Matrix();
m.postScale(scalefactorH, scalefactorV);

//Apply the matrix to a RectF
RectF crop = new RectF(mCropBoxRect);
m.mapRect(crop);

//And finally hit the bitmap with this diddy
bmp = Bitmap.createBitmap(this.mOriginalBitmap, (int)crop.left - mOffsetX, (int)crop.top - mOffsetY, (int)crop.width() - mOffsetX, (int)crop.height() - mOffsetY);