Advertisement
Guest User

Untitled

a guest
Aug 18th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. public final class BitmapUtility {
  2.  
  3. private BitmapUtility() {
  4.  
  5. }
  6.  
  7. // scale the bitmap for a given maximum dimension
  8. // (width or height depending on the image's aspect ratio)
  9. public static Bitmap scaleBitmap(Bitmap bitmap, int dp, Context context) {
  10. int width = bitmap.getWidth();
  11. int height = bitmap.getHeight();
  12. int bounding = dpToPx(dp, context);
  13.  
  14. // Determine how much to scale: the dimension requiring less scaling is
  15. // closer to the its side. This way the image always stays inside your
  16. // bounding box AND either x/y axis touches it.
  17. float xScale = ((float) bounding) / width;
  18. float yScale = ((float) bounding) / height;
  19. float scale = (xScale <= yScale) ? xScale : yScale;
  20.  
  21. // Create a matrix for the scaling and add the scaling data
  22. Matrix matrix = new Matrix();
  23. matrix.postScale(scale, scale);
  24.  
  25. return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
  26. }
  27.  
  28. // convert from device-dependent density pixels to raw pixels
  29. private static int dpToPx(int dp, Context context) {
  30. float density = context.getResources().getDisplayMetrics().density;
  31. return Math.round((float) dp * density);
  32. }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement