Android以编程方式加载drawable并调整其大小
如何从InputStream(资产、文件系统)加载drawable并根据屏幕分辨率hdpi、mdpi或ldpi动态调整其大小 原始图像是hdpi,我只需要调整mdpi和ldpi的大小 Android是如何在/res中动态调整可绘图项的大小的?找到了它:Android以编程方式加载drawable并调整其大小,android,image,drawable,Android,Image,Drawable,如何从InputStream(资产、文件系统)加载drawable并根据屏幕分辨率hdpi、mdpi或ldpi动态调整其大小 原始图像是hdpi,我只需要调整mdpi和ldpi的大小 Android是如何在/res中动态调整可绘图项的大小的?找到了它: /** * Loads image from file system. * * @param context the application context * @param filename the filenam
/**
* 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);
如果您想显示一幅图像,但不幸的是,这幅图像的大小很大,例如,您想以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)
这很好,也很简单(其他答案对我不适用),发现:
Android文档可用。加载图片并将其设置为imageview后 您可以使用LayoutParams调整图像大小以匹配父对象 像这样
android.view.ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
layoutParams.width =MATCH_PARENT;
layoutParams.height =MATCH_PARENT;
imageView.setLayoutParams(layoutParams);
出于好奇,有没有理由不预先调整它的大小(对于
mdpi
和ldpi
)并在res
目录中链接到它?从网络下载的图像。我可以在服务器上做预处理,但下载速度会慢一些。不幸的是,这段代码在HTC Desire HD和HTC Evo上不起作用。请参见此处的解决方案:
android.view.ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
layoutParams.width =MATCH_PARENT;
layoutParams.height =MATCH_PARENT;
imageView.setLayoutParams(layoutParams);