Android以可编程方式加载drawable并调整其大小

如何从InputStream(资产,文件系统)加载drawable,并根据屏幕分辨率hdpi,mdpi或ldpidynamic调整它的大小?

原始图像是在HDL,我只需要resize为mdpi和ldpi。

有谁知道Android如何dynamicresize的绘图在/ res?

Solutions Collecting From Web of "Android以可编程方式加载drawable并调整其大小"

这很好,很容易(其他答案不适合我),在这里find:

  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文档可以在这里find 。

find了:

  /** * 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 (Throwable e) { // handle } finally { if (is != null) { try { is.close(); } catch (Throwable e1) { // ingore } } } return drawable; } 

像这样使用:

 loadImageFromFilesystem(context, filename, DisplayMetrics.DENSITY_MEDIUM); 

如果你想显示一幅图像,但不幸的是这个图像的尺寸很大,例如,你想显示一个30×30格式的图像,然后检查它的大小,如果它大于你需要的大小,然后除以你的数量(这里是30 * 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) 

加载你的图片并将其设置为imageview后,您可以使用layoutparam来将图片的大小设置为match_parent

喜欢这个

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