bas*_*sin 4 android resize image-resizing
我的应用程序包含带有图像的按钮,使用setCompoundDrawablesWithIntrinsicBounds设置.我使用app的drawables文件夹中的图像,但也使用从网上下载并存储在SD卡上的图像.我发现我需要升级SD卡图像,这样它们的渲染大小与drawables中的图像大小相同.我这样做使用:
Options opts = new BitmapFactory.Options();
opts.inDensity = 160;
Bitmap bm = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() +
context.getResources().getString(R.string.savefolder) + iconfile, opts);
myIcon = new BitmapDrawable(context.getResources(), bm);
btn.setCompoundDrawablesWithIntrinsicBounds(myIcon, null, null, null );
Run Code Online (Sandbox Code Playgroud)
这一直没有问题,直到我将手机更新到Android 4.1.1并注意到下载的图像现在出现的尺寸比可绘制文件夹的图像小得多.
我使用inDensity值搞砸了很小的效果,但是根据btnheight值(只是图像所在按钮的高度)缩放位图更成功:
int intoffset=bm.getHeight() - bm.getWidth();
myIcon = new BitmapDrawable(context.getResources(),
Bitmap.createScaledBitmap(bm, btnheight - (((btnheight/100)*10) +
intoffset) , btnheight - ((btnheight/100)*10), true));
Run Code Online (Sandbox Code Playgroud)
这种作品,但图像仍然比它所在的按钮大一点(根据上述情况,情况应该不是这样,因为它应该将图像高度缩放到按钮高度的90%.)I做了这个测试.我不能在我的应用程序中使用此方法,因为按钮高度根据按钮上显示的字体大小而变化,并且用户可以在应用程序首选项中更改此字体大小.
顺便说一下,奇怪的是(?),通过将位图缩放到原始高度的两倍来使用
Bitmap.createScaledBitmap(bm, bm.getWidth() * 2
, bm.getHeight() * 2, true));
Run Code Online (Sandbox Code Playgroud)
它在4.0.3和4.1.1中正确呈现(好吧,它显示的尺寸与可绘制的图标大小相同),但在2.1中表现得如你所期望的那样(渲染得比它所在的按钮大).
如果有人对4.1.1中为什么会发生这种情况有任何见解,我可以这样做,我的decodeFile位图呈现与我的可绘制位图相同的大小,而不必单独编写4.1.1代码,我将不胜感激!
修改我的原始代码如下所示适用于4.1.1以及之前测试过的版本......
Options opts = new BitmapFactory.Options();
DisplayMetrics dm = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(dm);
int dpiClassification = dm.densityDpi;
opts.inDensity = dm.DENSITY_MEDIUM;
opts.inTargetDensity = dpiClassification;
opts.inScaled =true;
Bitmap bm = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() +
context.getResources().getString(R.string.savefolder) + iconfile, opts);
myIcon = new BitmapDrawable(context.getResources(), bm);
btn.setCompoundDrawablesWithIntrinsicBounds(myIcon, null, null, null );
Run Code Online (Sandbox Code Playgroud)