项目中有个图片在平板电脑中显示特别小的原因,一直苦于没找到原因,也没有平板电脑测试,今天找了个修改分辨率的,编写相关方法终于处理了,记录下比较:
好让以后不造轮子。
主要是获取文章相关图片显示问题,直接用getIntrinsicWidth()方法获取,getIntrinsicWidth()获取的并非图片的实际宽度,在手机看还过得去,不会相差太远,但在平板电脑看,
它简直就是一个小女孩,太害羞了,以至于显示那么小。
回到正题:
解决方法:
1.获取手机分辨率 用该分辨率乘以其密度
if (file.exists()) { // 如果文件已经存在,直接返回 Drawable drawable = Drawable.createFromPath(savePath); DisplayMetrics dm = new DisplayMetrics(); //获取手机屏幕分辨率 dm = context.getResources().getDisplayMetrics(); //屏幕实际大小 // int screenWidth = dm.widthPixels; // int screenHeight = dm.heightPixels; float density = dm.density; //图片实际大小 int imgWidth = (int) (drawable.getIntrinsicWidth() *density); int imgHeight = (int)( drawable.getIntrinsicHeight() * density); //drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.setBounds(0, 0, imgWidth,imgHeight); //} return drawable; }
没有图片时加载
private void setDrawable(Drawable nDrawable) { drawable = nDrawable; //drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); //setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); DisplayMetrics dm = new DisplayMetrics(); //获取手机屏幕分辨率 dm = context.getResources().getDisplayMetrics(); //屏幕实际大小 // int screenWidth = dm.widthPixels; // int screenHeight = dm.heightPixels; float density = dm.density; //图片实际大小 int imgWidth = (int) (drawable.getIntrinsicWidth() *density); int imgHeight = (int)( drawable.getIntrinsicHeight() * density); //drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.setBounds(0, 0, imgWidth,imgHeight); setBounds(0, 0, imgWidth, imgHeight); //注意加上,不加会出现图片和文字混淆在一起 }
原文地址:http://hongshengpeng.com/article/show/254.aspx
Android获取图片实际大小兼容平板电脑,码迷,mamicode.com
时间: 2024-10-19 05:07:28