Android以编程方式加载drawable并调整其大小
问题描述:
如何从InputStream(资产,文件系统)加载drawable并根据屏幕分辨率hdpi,mdpi或ldpi动态调整其大小?
How can I load drawable from InputStream (assets, file system) and resize it dynamically based on the screen resolution hdpi, mdpi or ldpi?
原始图像为hdpi,我只需要调整mdpi和ldpi的大小即可.
The original image is in hdpi, I only need resizing for mdpi and ldpi.
Android如何在/res中动态调整可绘制对象的大小?
How does Android do dynamic resizing of the drawables in /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);