Android如何通过编程加载Drawable并调整其大小

9

我该如何从InputStream(assets,文件系统)中加载drawable,并根据屏幕分辨率hdpi、mdpi或ldpi动态调整其大小?

原始图像为hdpi,我只需要将其调整为mdpi和ldpi。

Android如何对/res中的可绘制对象进行动态调整大小?


出于好奇,不预先调整大小(对于mdpildpi)并将其链接到res目录中的任何原因吗? - Marvin Pinto
从网络下载的图像。我可以在服务器上进行预处理,但下载速度会变慢。 - peceps
4个回答

10

这很不错且简单(其他答案对我没有用),在这里找到:

  ImageView iv = (ImageView) findViewById(R.id.imageView);
  Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.picture);
  Bitmap bMapScaled = Bitmap.createScaledBitmap(bMap, newWidth, newHeight, true);
  iv.setImageBitmap(bMapScaled);

Android文档可以在这里找到。


5

找到了:

  /**
   * Loads image from file system.
   * 
   * @param context the application context
   * @param filename the filename of the image
   * @param originalDensity the density of the image, it will be automatically
   * resized to the device density
   * @return image drawable or null if the image is not found or IO error occurs
   */
  public static Drawable loadImageFromFilesystem(Context context, String filename, int originalDensity) {
    Drawable drawable = null;
    InputStream is = null;

    // set options to resize the image
    Options opts = new BitmapFactory.Options();
    opts.inDensity = originalDensity;

    try {
      is = context.openFileInput(filename);
      drawable = Drawable.createFromResourceStream(context.getResources(), null, is, filename, opts);         
    } catch (Exception e) {
      // handle
    } finally {
      if (is != null) {
        try {
          is.close();
        } catch (Exception e1) {
          // log
        }
      }
    }
    return drawable;
  }

使用方法如下:

loadImageFromFilesystem(context, filename, DisplayMetrics.DENSITY_MEDIUM);

1
很遗憾,这段代码在HTC Desire HD和HTC Evo上无法运行。请参见此处的解决方案:https://dev59.com/31zUa4cB1Zd3GeqP0Sv7#9195531 - peceps

4

如果您想显示一张图片,但不幸的是这张图片太大了,比如说,您想以30x30格式显示一张图片,那么请检查它的大小是否超过您所需的大小,如果是,则将其除以您的数量(在这种情况下为30 x 30),然后再次使用所得到的结果来划分图像区域。

drawable = this.getResources().getDrawable(R.drawable.pirImg);
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
if (width > 30)//means if the size of an image is greater than 30*30
{
  width = drawable.getIntrinsicWidth() / 30;
  height = drawable.getIntrinsicWidth() / 30;
}

drawable.setBounds(
    0, 0, 
    drawable.getIntrinsicWidth() / width, 
    drawable.getIntrinsicHeight() / height);

//and now add the modified image in your overlay
overlayitem[i].setMarker(drawable)

0

在加载图片并将其设置为ImageView之后,您可以使用LayoutParam来将图像大小设置为match_parent

就像这样

android.view.ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
layoutParams.width =MATCH_PARENT;
layoutParams.height =MATCH_PARENT;
imageView.setLayoutParams(layoutParams);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接