当前位置: 首页 > 新闻动态 > 软件编程

Android开发实现ImageView宽度顶边显示,高度保持比例的方法

作者:用户投稿 浏览: 发布日期:2026-01-11
[导读]:这篇文章主要介绍了Android开发实现ImageView宽度顶边显示,高度保持比例的方法,结合实例形式分析了Android ImageView界面布局及元素属性动态操作两种功能实现技巧,需要的朋友可以参考下

本文实例讲述了Android开发实现ImageView宽度顶边显示,高度保持比例的方法。分享给大家供大家参考,具体如下:

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

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

更多关于Android相关内容感兴趣的读者可查看本站专题:《Android开发入门与进阶教程》、《Android调试技巧与常见问题解决方法汇总》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结》

希望本文所述对大家Android程序设计有所帮助。

免责声明:转载请注明出处:http://www.sczxchw.cn/news/314921.html

扫一扫高效沟通

多一份参考总有益处

免费领取网站策划SEO优化策划方案

请填写下方表单,我们会尽快与您联系
感谢您的咨询,我们会尽快给您回复!