android中,很多时候需要将图片的宽度设置为屏幕宽度,然后让高度等比例缩放。我自己写了一下,效果是想要的那样,所以记下来分享给大家。
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.img); //资源文件中的一张图片
WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
int width = wm.getDefaultDisplay().getWidth(); //获取屏幕的宽度
imageView.measure(0,0); //这一步很重要
int height = imageView.getMeasuredHeight() * width / imageView.getMeasuredWidth(); //这里就是将高度等比例缩放,其中imageView.getMeasuredHeight()和imageView.getMeasuredWidth()是计算图片本身的宽高
imageView.setLayoutParams(new ViewGroup.LayoutParams(width, height));
关于怎样测量控件的宽高,可以参考博客http://blog.youkuaiyun.com/shirly_yy/article/details/53535438