2014-09-26 68 views
0

我正在嘗試裁剪位圖。我首先縮放原始位圖以適應視圖內容,然後在視圖上繪製一個矩形,用戶可以四處移動並縮放以裁剪圖像,就像從Instagram導入圖片時可以在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

我能夠通過使用矩陣得到它的工作。答案很簡單,只是到達那裏對我來說很困難。

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