ImageView 宽度顶边显示,高度保持比例

来源:互联网 发布:软件规模度量单位 编辑:程序博客网 时间:2024/03/28 22:49

图片宽度顶边显示,高度保持比例

1、再布局中设置

<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"/>

主要是代码:

android:scaleType="fitXY" :填充宽度match_parent

android:adjustViewBounds="true" :高度保持比例


2、代码实现

    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);              }          }      }  



0 0