Skip to content

Instantly share code, notes, and snippets.

@KKorvin
Created August 24, 2016 13:36
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 KKorvin/d2ef4cac316633355ff7b145f82ee979 to your computer and use it in GitHub Desktop.
Save KKorvin/d2ef4cac316633355ff7b145f82ee979 to your computer and use it in GitHub Desktop.
Scaling Bitmap on the fly. For Android, including main thread, background thread and Glide examples.
//Scale function:
/**
* Creates new bitmap by scaling given one
*
* @param scaleFactor
* @param bitmap
* @return new bitmap
*/
public static Bitmap createScaledBitmap(Bitmap bitmap, float scaleFactor) {
Matrix m = new Matrix();
m.setRectToRect(new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight()),
new RectF(0, 0, bitmap.getWidth() * scaleFactor, bitmap.getHeight() * scaleFactor), Matrix.ScaleToFit.CENTER);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
}
// Example of usage im main thread:
Bitmap scaledBitmap = UIHelper.createScaledBitmap(letterTile, 2f);
// Example of usage in background thread
new Thread(new Runnable() {
@Override
public void run() {
final Bitmap scaledBitmap = createScaledBitmap(letterTile, 2f);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
anyImageView.setImageBitmap(scaledBitmap);
}
});
}
}).run();
//Example of usage with Glide:
Glide.with(getActivity()).load(playableItem.getCoverImageUrl()).crossFade().into(new GlideDrawableImageViewTarget(imgDetailedTopCover) {
@Override
public void onResourceReady(GlideDrawable drawable, GlideAnimation anim) {
super.onResourceReady(drawable, anim);
Bitmap bitmap = ((GlideBitmapDrawable) drawable).getBitmap();
anyImageView.setImageBitmap(createScaledBitmap(bitmap, 2f));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment