Skip to content

Instantly share code, notes, and snippets.

@goofyahead
Forked from nesquena/BitmapScaler.java
Last active September 7, 2016 12:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goofyahead/32af46cadfc0c3686c3ed1375c518258 to your computer and use it in GitHub Desktop.
Save goofyahead/32af46cadfc0c3686c3ed1375c518258 to your computer and use it in GitHub Desktop.
Easy utility for scaling bitmaps
public class BitmapScaler
{
// scale and keep aspect ratio
public static Bitmap scaleToFitWidth(Bitmap b, int width)
{
float factor = width / (float) b.getWidth();
return Bitmap.createScaledBitmap(b, width, (int) (b.getHeight() * factor), true);
}
// scale and keep aspect ratio
public static Bitmap scaleToFitHeight(Bitmap b, int height)
{
float factor = height / (float) b.getHeight();
return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factor), height, true);
}
// scale and keep aspect ratio
public static Bitmap scaleToFill(Bitmap b, int width, int height)
{
float factorH = height / (float) b.getHeight();
float factorW = width / (float) b.getWidth();
float factorToUse = (factorH > factorW) ? factorW : factorH;
return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factorToUse),
(int) (b.getHeight() * factorToUse), true);
}
// scale and don't keep aspect ratio
public static Bitmap strechToFill(Bitmap b, int width, int height)
{
float factorH = height / (float) b.getHeight();
float factorW = width / (float) b.getWidth();
return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factorW),
(int) (b.getHeight() * factorH), true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment