Skip to content

Instantly share code, notes, and snippets.

@jpardogo
Last active June 11, 2020 08:09
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save jpardogo/7146143 to your computer and use it in GitHub Desktop.
Save jpardogo/7146143 to your computer and use it in GitHub Desktop.
Resize a bitmap respecting the aspect radio. I use a custom transformations with Picasso library. This transformation calculate the new dimension of the bitmap scaling it to fit a specific width or height that we pass as a parameter (usually the biggest size of the imageView where we wanna set the bitmap).
public class ScaleToFitWidthHeightTransform implements Transformation {
private int mSize;
private boolean isHeightScale;
public ScaleToFitWidthHeightTransform(int size, boolean isHeightScale){
mSize =size;
this.isHeightScale = isHeightScale;
}
@Override
public Bitmap transform(Bitmap source) {
float scale;
int newSize;
Bitmap scaleBitmap;
if(isHeightScale){
scale = (float) mSize / source.getHeight();
newSize = Math.round(source.getWidth() * scale);
scaleBitmap= Bitmap.createScaledBitmap(source, newSize, mSize, true);
}else{
scale = (float) mSize / source.getWidth();
newSize = Math.round(source.getHeight() * scale);
scaleBitmap = Bitmap.createScaledBitmap(source, mSize,newSize, true);
}
if (scaleBitmap != source) {
source.recycle();
}
return scaleBitmap;
}
@Override
public String key() {
return "scaleRespectRatio" + mSize + isHeightScale;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment