Skip to content

Instantly share code, notes, and snippets.

@dymx101
Created September 19, 2014 01:41
Show Gist options
  • Save dymx101/e46fb261d20cba468939 to your computer and use it in GitHub Desktop.
Save dymx101/e46fb261d20cba468939 to your computer and use it in GitHub Desktop.
Android imageview auto fit screen width
I had a similar problem once. I solved it by making a custom ImageView.
public class CustomImageView extends ImageView
Then override the onMeasure method of the imageview. I did something like this I believe:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
try {
Drawable drawable = getDrawable();
if (drawable == null) {
setMeasuredDimension(0, 0);
} else {
float imageSideRatio = (float)drawable.getIntrinsicWidth() / (float)drawable.getIntrinsicHeight();
float viewSideRatio = (float)MeasureSpec.getSize(widthMeasureSpec) / (float)MeasureSpec.getSize(heightMeasureSpec);
if (imageSideRatio >= viewSideRatio) {
// Image is wider than the display (ratio)
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = (int)(width / imageSideRatio);
setMeasuredDimension(width, height);
} else {
// Image is taller than the display (ratio)
int height = MeasureSpec.getSize(heightMeasureSpec);
int width = (int)(height * imageSideRatio);
setMeasuredDimension(width, height);
}
}
} catch (Exception e) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
This will stretch the image to fit the screen while maintaining the aspect ratio.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment