SoFunction
Updated on 2025-03-11

Android development method to realize the top edge display of ImageView width and maintain the proportion of height

This article describes the method of Android development to realize the top edge display of ImageView width and maintain the proportion of height. Share it for your reference, as follows:

ImageView The top edge of the image width is displayed, the height remains proportional

1. Set in the layout

<ImageView
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:paddingLeft="5dp"
  android:paddingRight="2.5dp"
  android:layout_weight="1"
  android:scaleType="fitXY"
  android:adjustViewBounds="true"
  android:src="@drawable/default_wallpaper_collection_cover"/>

Mainly the code:

android:scaleType="fitXY":Fill width match_parent
android:adjustViewBounds="true": Height-maintaining proportion

2. Code implementation

public class MImageView extends ImageView {
  public MImageView(Context context) {
    super(context);
  }
  public MImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }
  public MImageView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
  }
  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    Drawable drawable = getDrawable();
    if (drawable != null) {
      int width = (widthMeasureSpec);
      int height = (int) ((float) width * (float) () / (float) ());
      setMeasuredDimension(width, height);
    } else {
      (widthMeasureSpec, heightMeasureSpec);
    }
  }
}

For more information about Android related content, please check out the topic of this site:Android development introduction and advanced tutorial》、《Android debugging skills and solutions to common problems》、《Summary of the usage of basic Android components》、《Android View View Tips Summary》、《Android layout layout tips summary"and"Android control usage summary

I hope this article will be helpful to everyone's Android programming design.