【问题标题】:Scaling a rectangle up to match a bitmap放大矩形以匹配位图
【发布时间】:2014-09-26 16:05:55
【问题描述】:

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

正方形的中间是最终结果应该是什么

以及我们实际得到的结果:

我知道这只是数学问题,但我昨晚花了几个小时试图弄明白。我做错了什么?

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

【问题讨论】:

    标签: android image bitmap android-bitmap


    【解决方案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);
    

    【讨论】:

    • 请在此定义什么是 mBmpScaledForView。我得到 mOriginalBitmap 是原始位图,而 mOffsetX 和 mOffsetY 是某种固定值。
    • 请问你如何计算 mOffsetX 和 mOffsetY ?
    猜你喜欢
    • 2014-06-14
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    • 1970-01-01
    • 2013-08-14
    • 2011-09-19
    相关资源
    最近更新 更多