我该如何从InputStream(assets,文件系统)中加载drawable,并根据屏幕分辨率hdpi、mdpi或ldpi动态调整其大小?
原始图像为hdpi,我只需要将其调整为mdpi和ldpi。
Android如何对/res中的可绘制对象进行动态调整大小?
找到了:
/**
* 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);
如果您想显示一张图片,但不幸的是这张图片太大了,比如说,您想以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)
在加载图片并将其设置为ImageView之后,您可以使用LayoutParam来将图像大小设置为match_parent
就像这样
android.view.ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
layoutParams.width =MATCH_PARENT;
layoutParams.height =MATCH_PARENT;
imageView.setLayoutParams(layoutParams);
mdpi
和ldpi
)并将其链接到res
目录中的任何原因吗? - Marvin Pinto