Skip to content

Instantly share code, notes, and snippets.

@brandhill
Created November 14, 2014 07:08
Show Gist options
  • Save brandhill/290b099416fcdcb72cc6 to your computer and use it in GitHub Desktop.
Save brandhill/290b099416fcdcb72cc6 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;
public class DynamicImageView extends ImageView {
public DynamicImageView(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
final Drawable d = this.getDrawable();
if (d != null) {
// ceil not round - avoid thin vertical gaps along the left/right edges
final int width = MeasureSpec.getSize(widthMeasureSpec);
final int height = (int) Math.ceil(width * (float) d.getIntrinsicHeight() / d.getIntrinsicWidth());
this.setMeasuredDimension(width, height);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment