Skip to content

Instantly share code, notes, and snippets.

@sephiroth74
Last active December 2, 2015 17:05
Show Gist options
  • Save sephiroth74/c224a5571f8c4c5f2d5c to your computer and use it in GitHub Desktop.
Save sephiroth74/c224a5571f8c4c5f2d5c to your computer and use it in GitHub Desktop.
Always draw the given bitmap into the Drawable's bounds, respecting the bitmap's aspect ratio. Best use with an ImageView with scaleType set to FIT_XY
/**
* Always draw the given bitmap into the Drawable's bounds, respecting
* the bitmap's aspect ratio.
* Best use with an ImageView with scaleType set to FIT_XY
*/
public class FitBitmapDrawable extends BitmapDrawable {
private final Matrix matrix = new Matrix();
private final RectF mTempSrc = new RectF();
private final RectF mTempDst = new RectF();
private final float[] mScale = new float[2];
private boolean mHaveFrame;
public FitBitmapDrawable(Resources res, Bitmap bitmap) {
super(res, bitmap);
}
@Override
protected void onBoundsChange(final Rect bounds) {
super.onBoundsChange(bounds);
mTempSrc.set(0, 0, getIntrinsicWidth(), getIntrinsicHeight());
mTempDst.set(0, 0, getBounds().width(), getBounds().height());
mScale[0] = mTempSrc.width() / mTempDst.width();
mScale[1] = mTempSrc.height() / mTempDst.height();
matrix.setRectToRect(mTempSrc, mTempDst, Matrix.ScaleToFit.CENTER);
mHaveFrame = true;
}
@Override
public void draw(final Canvas canvas) {
if (mHaveFrame) {
int count = canvas.getSaveCount();
canvas.save();
canvas.concat(matrix);
canvas.scale(mScale[0], mScale[1]);
super.draw(canvas);
canvas.restoreToCount(count);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment