缩放后获取ImageView的位图

时间:2016-07-01 19:40:32

标签: android bitmap

当我从ImageView中获取Bitmap时,我ScaleType的{​​{1}}和FitXYBitmap

Imageview

返回的是原始Bitmap currentBitmap = ((BitmapDrawable) context.getDrawable()).getBitmap(); 原始Image而不是Width/Height,如何才能使Scaled Size Scaled不是原来的Bitmap

1 个答案:

答案 0 :(得分:1)

嗯,缩放效果实际上是在Canvas级别应用的。因此,您可以做的是获取当前的Canvas扩充,然后将您的Bitmap绘制为带有更改的新Bitmap,但是,您将不得不重写ImageView类以暴露支持Canvas的Matrix。 / p>

public class ExposedImageView extends ImageView {
    protected Matrix matrix = new Matrix();

    ... // constructors

    @Override
    public void onDraw(Canvas canvas){
        super.onDraw(canvas);

        canvas.getMatrix(matrix);
    }

    public Matrix getCanvasMatrix(){
        return matrix;
    }
} 

然后你可以通过以下方式获得调整后的图像:

public static Bitmap getRealImage(ExposedImageView view) throws Throwable { // OutOfMemoryError, etc.
    Bitmap original = ((BitmapDrawable) context.getDrawable())
        .getBitmap();

    Bitmap adjusted = Bitmap.createBitmap(original.getWidth(),
        original.getHeight(), 
        original.getConfig());

    Canvas canvas = new Canvas(adjusted);
    canvas.setMatrix(view.getCanvasMatrix());
    canvas.drawBitmap(original, 0, 0, null);

    return adjusted;
}