/** * 高度自适应ImageView,高度始终充满显示区域,宽度成比例缩放 */public class AutoHeightImageView extends ImageView {    public AutoHeightImageView(Context context) {        super(context);    }    public AutoHeightImageView(Context context, AttributeSet attrs) {        super(context, attrs);    }    public AutoHeightImageView(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 = drawable.getMinimumWidth();                int height = drawable.getMinimumHeight();                float scale = (float)width/height;                //强制根据图片原有比例,重新计算ImageView显示区域宽度                int heightMeasure = MeasureSpec.getSize(heightMeasureSpec);                int widthMeasure = (int)(heightMeasure * scale);                //并设置为MeasureSpec.EXACTLY精确模式保证之后的super.onMeasure()不再调整                widthMeasureSpec = MeasureSpec.makeMeasureSpec(widthMeasure, MeasureSpec.EXACTLY);            }            super.onMeasure(widthMeasureSpec, heightMeasureSpec);    }}

相反地,如果是宽度自适应,高度成比例缩放的话,使用以下代码:

/** * 宽度自适应ImageView,宽度始终充满显示区域,高度成比例缩放 */public class AutoScaleWidthImageView extends ImageView {    public AutoScaleWidthImageView (Context context, AttributeSet attrs) {        super(context, attrs);    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {         Drawable drawable = getDrawable();         if(drawable != null){             int width = drawable.getMinimumWidth();             int height = drawable.getMinimumHeight();             float scale = (float)height/width;             int widthMeasure = MeasureSpec.getSize(widthMeasureSpec);             int heightMeasure = (int)(widthMeasure*scale);             heightMeasureSpec =  MeasureSpec.makeMeasureSpec(heightMeasure, MeasureSpec.EXACTLY);         }        super.onMeasure(widthMeasureSpec, heightMeasureSpec);    }}

更多相关文章

  1. android图片缩放(指定大小) drawable获取图片后怎么设置图片大小
  2. Android 对一个View进行缩放处理(放大或缩小View)案例
  3. Android缩放drawable
  4. iPhone、Android 社交 App 使用比例大調查(資訊圖表)
  5. Android之UI学习篇六:ImageView实现图片旋转和缩放
  6. Android中获取文本宽度和高度

随机推荐

  1. Android(安卓)7.0动态权限大总结
  2. android-屏幕适配(一)
  3. 传智播客揭秘Android(安卓)6.0之Direct S
  4. 从Android(安卓)L默认ART虚拟机看国内手
  5. 将Android(安卓)Studio的设置恢复到初始
  6. android启动第一个界面时即闪屏的核心代
  7. 传HTC“超音速”手机将搭载Android(安卓)
  8. Android开发之使用Preferences设计软件设
  9. Android(安卓)学习笔记(封贴,放弃安卓)
  10. android实现3D效果翻页