Skip to content

Instantly share code, notes, and snippets.

@willblaschko
Last active September 19, 2016 05:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willblaschko/7ac4b3cf9467c436f42c946c5e34585f to your computer and use it in GitHub Desktop.
Save willblaschko/7ac4b3cf9467c436f42c946c5e34585f to your computer and use it in GitHub Desktop.
A Glide transformation to set the center of the crop()--similar to cropCenter(). This only affects the overflow dimension, not the fit dimension.
/**
*
* Most of this from:
* https://github.com/bumptech/glide/blob/master/library/src/main/java/com/bumptech/glide/load/resource/bitmap/CenterCrop.java
* and
* https://github.com/bumptech/glide/blob/master/library/src/main/java/com/bumptech/glide/load/resource/bitmap/TransformationUtils.java
*
* Created by wblaschko on 3/31/16.
*/
public class LocationBitmapTransformation extends BitmapTransformation {
public static final int PAINT_FLAGS = Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG;
private static final Paint DEFAULT_PAINT = new Paint(PAINT_FLAGS);
float mPercentX = .5f;
float mPercentY = .5f;
public LocationBitmapTransformation(Context context, float percentX, float percentY){
super(context);
mPercentX = percentX;
mPercentY = percentY;
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap inBitmap, int width, int height) {
int bitmapWidth = inBitmap.getWidth();
int bitmapHeight = inBitmap.getHeight();
if (bitmapWidth == width && bitmapHeight == height) {
return inBitmap;
}
//From ImageView/Bitmap.createScaledBitmap.
final float scale;
float dx = 0, dy = 0;
Matrix m = new Matrix();
if (bitmapWidth * height > width * bitmapHeight) {
scale = (float) height / (float) bitmapHeight;
dx = (width - inBitmap.getWidth() * scale) * mPercentX;
} else {
scale = (float) width / (float) bitmapWidth;
dy = (height - inBitmap.getHeight() * scale) * mPercentY;
}
m.setScale(scale, scale);
m.postTranslate((int) (dx + 0.5f), (int) (dy + 0.5f));
Bitmap result = Bitmap.createBitmap(width, height, getSafeConfig(inBitmap));
Canvas canvas = new Canvas(result);
canvas.drawBitmap(inBitmap, m, DEFAULT_PAINT);
return result;
}
@Override
public String getId() {
return new StringBuilder("locationtransform")
.append((int) mPercentX * 100)
.append("x")
.append((int) mPercentY * 100)
.toString();
}
private static Bitmap.Config getSafeConfig(Bitmap bitmap) {
return bitmap.getConfig() != null ? bitmap.getConfig() : Bitmap.Config.ARGB_8888;
}
}
Glide.with(this)
.load(R.drawable.corgi2)
.transform(new LocationBitmapTransformation(this, .1f, .9f))
.into(corgi1);
<ImageView
android:layout_width="400dp"
android:layout_height="200dp"
android:id="@+id/corgi1"
android:layout_margin="20dp"/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment