<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:src="@drawable/photo" />
If you want to have an image's width matches to the screen width and have the height change dynamically. Above is how to code. (scaleType="fitXY") also works.
Not so simple!
Although the code works on the most Android devices, it doesn't work on some devices (such as Samsung S4).
Here's the solution:
<com.example.code.KeepRatioImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:src="@drawable/photo" />
public class KeepRatioImageView extends ImageView {
public KeepRatioImageView(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) {
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);
}
}
}
No comments:
Post a Comment