Scaled Bitmap maintaining aspect ratio

后端 未结 12 911
-上瘾入骨i
-上瘾入骨i 2020-11-30 23:49

I would like to scale a Bitmap to a runtime dependant width and height, where the aspect ratio is maintained and the Bitmap fills the entire width

12条回答
  •  旧巷少年郎
    2020-12-01 00:38

    This is an awesome library from ArthurHub to handle the image crops both programmatically and interactively if you don't want to reinvent the wheel.

    But if you prefer a non bloated version like me.., the internal function shown here is a rather sophisticated to perform Image Scaling with few standard options

    /**
     * Resize the given bitmap to the given width/height by the given option.
    */ enum RequestSizeOptions { RESIZE_FIT, RESIZE_INSIDE, RESIZE_EXACT } static Bitmap resizeBitmap(Bitmap bitmap, int reqWidth, int reqHeight, RequestSizeOptions options) { try { if (reqWidth > 0 && reqHeight > 0 && (options == RequestSizeOptions.RESIZE_FIT || options == RequestSizeOptions.RESIZE_INSIDE || options == RequestSizeOptions.RESIZE_EXACT)) { Bitmap resized = null; if (options == RequestSizeOptions.RESIZE_EXACT) { resized = Bitmap.createScaledBitmap(bitmap, reqWidth, reqHeight, false); } else { int width = bitmap.getWidth(); int height = bitmap.getHeight(); float scale = Math.max(width / (float) reqWidth, height / (float) reqHeight); if (scale > 1 || options == RequestSizeOptions.RESIZE_FIT) { resized = Bitmap.createScaledBitmap(bitmap, (int) (width / scale), (int) (height / scale), false); } } if (resized != null) { if (resized != bitmap) { bitmap.recycle(); } return resized; } } } catch (Exception e) { Log.w("AIC", "Failed to resize cropped image, return bitmap before resize", e); } return bitmap; }

提交回复
热议问题