【问题标题】:Resize images and setCompoundDrawablesWithIntrinsicBounds调整图像大小并设置CompoundDrawablesWithIntrinsicBounds
【发布时间】:2013-01-21 00:19:44
【问题描述】:

我的应用包含带有图像的按钮,使用 setCompoundDrawablesWithIntrinsicBounds 设置。我使用应用程序 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 );

这一直没有问题,直到我将手机更新到 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));

这种方法有效,但图像仍然比它所在的按钮大一点(根据上述情况,这不应该是这种情况,因为它应该将图像高度缩放到按钮高度的 90% .) 我这样做是为了测试。我不能在我的应用程序中使用此方法,因为按钮高度会根据按钮上显示的字体大小而变化,用户可以在应用程序首选项中更改此字体大小。

顺便说一句,我发现,奇怪的是(?),通过使用

将位图缩放到原始高度的两倍
   Bitmap.createScaledBitmap(bm, bm.getWidth() * 2
       , bm.getHeight() * 2, true));

它在 4.0.3 和 4.1.1 中正确渲染(嗯,它与可绘制图标的大小相同),但在 2.1 中表现得如您所愿(渲染得比它所在的按钮大) .

如果有人对为什么会在 4.1.1 中发生这种情况有任何见解,以及我可以做些什么以使我的 decodeFile 位图呈现与我的可绘制位图相同的大小,而无需单独为 4.1.1 编写代码,那将是非常感谢!

【问题讨论】:

    标签: android resize image-resizing


    【解决方案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 ); 
    

    【讨论】:

      猜你喜欢
      • 2016-08-21
      • 2011-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-20
      相关资源
      最近更新 更多