Android Development and Realization of ImageView Width Top Edge Display and Height Keeping Proportion Method

  • 2021-08-12 03:43:25
  • OfStack

In this paper, an example is given to describe the method of developing Android to realize the top edge display of ImageView width and keeping the proportion of height. Share it for your reference, as follows:

ImageView picture width is displayed at the top edge, and height is kept in proportion

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 retention ratio

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 = MeasureSpec.getSize(widthMeasureSpec);
      int height = (int) Math.ceil((float) width * (float) drawable.getIntrinsicHeight() / (float) drawable.getIntrinsicWidth());
      setMeasuredDimension(width, height);
    } else {
      super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
  }
}

More readers interested in Android can check the topics on this site: "Introduction and Advanced Tutorial of Android Development", "Summary of Android Debugging Skills and Common Problem Solutions", "Summary of Android Basic Component Usage", "Summary of Android View View Skills", "Summary of Android Layout layout Skills" and "Summary of Android Control Usage"

I hope this article is helpful to everyone's Android programming.


Related articles: