解决Bitmap通过getWidth和getHeight获取尺寸不符的问题
在使用BitmapFactory加载图片时,常会出现这种情况,返回的图片尺寸与实际尺寸不符。这是由于我们把图片资源放到res/drawable文件路径下时,选择的文件不同所致,不同的文件夹会有不同的缩放。
1、加载并显示图片
将70*98的图片放在res/drawable-hdpi中。
publicclassMainActivityextendsActivity{ TextViewtv_wl; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); tv_wl=(TextView)findViewById(R.id.tv_wl); Bitmapbm1=BitmapFactory.decodeResource(getResources(),R.drawable.img); intbm_width=bm1.getWidth(); intbm_height=bm1.getHeight(); tv_wl.setText("width="+bm_width+";height="+bm_height); } }
运行结果如下图所示:
这里尺寸和原图相同
2、修改文件存放路径
(1)放到res/drawable-mdpi下,运行效果如图
这里尺寸放大了1.5倍
(2)放到res/drawable-xhdpi下,运行效果如图
尺寸缩小了1.3倍
(3)放到res/drawable-xxdpi下,运行效果如图
尺寸缩小了2倍
3、寻找原因
电脑上图片尺寸,单位是像素。Android手机的屏幕分ldpi、mdpi、hdpi,甚至还有xhdpi,对于mdpi(density=160)设备,1dp=1px,对于hdpi(density=240)的设备,1dp=1.5px。所以,把图片放在了res/drawable-mdpi目录下,而运行的Android设备屏幕属于hdpi,导致图片尺寸会扩大1.5倍。
4、解决办法
(1)现在的Android设备一般都在hdpi及以上,所以建议把图片资源主要放在hdpi中。
(2)修改上述代码,设置缩放为false
BitmapFactory.OptionsbfoOptions=newBitmapFactory.Options(); bfoOptions.inScaled=false; Bitmapimg1=BitmapFactory.decodeResource(getResources(),R.drawable.img,bfoOptions); intbm_width=img1.getWidth(); intbm_height=img1.getHeight();
运行后你会发现,不论你将图片放在哪里,都是原尺寸。
补充知识:Android获取drawable中图片的高度宽度
1.定义一个ImageData类如下:
packagecom.example.vidarecyclerviewstagger; publicclassImageData{ privateintresourceId; privateintheight; privateintwidth; publicImageData(intresourceId,intheight,intwidth){ this.resourceId=resourceId; this.height=height; this.width=width; } publicintgetResourceId(){ returnresourceId; } publicvoidsetResourceId(intresourceId){ this.resourceId=resourceId; } publicintgetHeight(){ returnheight; } publicvoidsetHeight(intheight){ this.height=height; } publicintgetWidth(){ returnwidth; } publicvoidsetWidth(intwidth){ this.width=width; } }
2.在drawable中放置一些图片:
privatestaticint[]imgRes=newint[]{R.drawable.img1,R.drawable.img2,R.drawable.img3,R.drawable.img4, R.drawable.img5,R.drawable.img6,R.drawable.img7,R.drawable.img8, R.drawable.img9,R.drawable.img10,R.drawable.img11,R.drawable.img12, R.drawable.img13,R.drawable.img14,R.drawable.img15,R.drawable.img16};
3.获取每个图片的高度宽度并保存数据到mData中:
privateArrayListmData=newArrayList<>(); publicvoidInitData(){ for(inti=0;i 关键代码就这么几句:
BitmapFactory.Optionsoptions=newBitmapFactory.Options(); BitmapFactory.decodeResource(getResources(),imgRes[i],options); //获取图片的宽高 intheight=options.outHeight; intwidth=options.outWidth;以上这篇解决Bitmap通过getWidth和getHeight获取尺寸不符的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。