Skip to content

Instantly share code, notes, and snippets.

@neilbantoc
Last active August 29, 2015 13:56
Show Gist options
  • Save neilbantoc/8820907 to your computer and use it in GitHub Desktop.
Save neilbantoc/8820907 to your computer and use it in GitHub Desktop.
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
/*
* An ImageView that scales its bounds while following the aspect ratio
* of its drawable. This is useful for showing images in fill_parent
* situations when the drawable itself is smaller than the dimensions of
* the view.
*
* Normal ImageView with fill_parent and 20x20 image:
*
* 10px 20px 10px
* -----------------------
* | | | |
* | view | image | view | 20px
* | | | |
* ----------------------- *obviously not drawn to scale
*
* This ImageView with fill_parent and 20x20 image:
*
* 40px
* ---------------------
* | |
* | |
* | |
* | image | 40px
* | |
* | |
* | |
* --------------------- *not drawn to scale as well
*
*/
public class ResizableImageView extends ImageView {
public ResizableImageView(Context context) {
super(context);
}
public ResizableImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ResizableImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable drawable = getDrawable();
if (drawable != null) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int diw = drawable.getIntrinsicWidth();
if (diw > 0) {
int height = width * drawable.getIntrinsicHeight() / diw;
setMeasuredDimension(width, height);
} else
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
} else
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment