Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public final class BitmapUtility {
- private BitmapUtility() {
- }
- // scale the bitmap for a given maximum dimension
- // (width or height depending on the image's aspect ratio)
- public static Bitmap scaleBitmap(Bitmap bitmap, int dp, Context context) {
- int width = bitmap.getWidth();
- int height = bitmap.getHeight();
- int bounding = dpToPx(dp, context);
- // Determine how much to scale: the dimension requiring less scaling is
- // closer to the its side. This way the image always stays inside your
- // bounding box AND either x/y axis touches it.
- float xScale = ((float) bounding) / width;
- float yScale = ((float) bounding) / height;
- float scale = (xScale <= yScale) ? xScale : yScale;
- // Create a matrix for the scaling and add the scaling data
- Matrix matrix = new Matrix();
- matrix.postScale(scale, scale);
- return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
- }
- // convert from device-dependent density pixels to raw pixels
- private static int dpToPx(int dp, Context context) {
- float density = context.getResources().getDisplayMetrics().density;
- return Math.round((float) dp * density);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement