我正在开发一个包含许多图像的应用程序。由于应用程序限制(50MB),我将一些图像移至扩展文件。在我将所有图像放入不同的文件夹(如 drawable-xhdpi、drawable-mdpi 等)之前。现在我以编程方式确定手机的 dpi 并相应地获取图像。以下是重要的代码位:
public String getFolder()
{
String folder = "";
int dpi = res.getDisplayMetrics().densityDpi;
int widthPixels = metrics.widthPixels;
int heightPixels = metrics.heightPixels;
float scaleFactor = metrics.density;
float widthDp = widthPixels / scaleFactor;
float heightDp = heightPixels / scaleFactor;
float smallestWidth = Math.min(widthDp, heightDp);
if (smallestWidth > 720 && dpi == DisplayMetrics.DENSITY_MEDIUM) {
//Device is a 10" tablet
}
else if (dpi == DisplayMetrics.DENSITY_XHIGH||dpi == DisplayMetrics.DENSITY_TV) {
//Device is a 7" tablet
//xhdpi
folder = "drawable-xhdpi/";
}
else if((smallestWidth > 480 && dpi == DisplayMetrics.DENSITY_MEDIUM)|| dpi == DisplayMetrics.DENSITY_HIGH)
{
//hdpi
folder = "drawable-hdpi/";
}
else if(dpi == DisplayMetrics.DENSITY_XXHIGH)
{
//xxhdpi
folder = "drawable-xxhdpi/";
}
else if(dpi == DisplayMetrics.DENSITY_MEDIUM)
{
//mdpi
folder = "drawable-mdpi/";
}
else if(dpi == DisplayMetrics.DENSITY_LOW)
{
//ldpi
folder = "drawable-ldpi/";
}
return folder;
}
public BitmapDrawable getDrawable(Context ctx, String imageName){
String path = folder+imageName;
ZipResourceFile zip;
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap b = null;
try {
zip = APKExpansionSupport.getAPKExpansionZipFile(ctx, 9, -1);
InputStream is = zip.getInputStream(path);
b = BitmapFactory.decodeStream(is, null, bfo); }
catch (IOException e) {
e.printStackTrace();
}
return new BitmapDrawable(b);
}
因此,每当我需要图像时,我都会像这样调用 getDrawable:
newItem.setBackgroundDrawable(storage.getDrawable(this,"red_stored.png"));
但问题是,现在当我以编程方式执行此操作时,图像看起来比我将其放入 drawable-xhdpi 文件夹并且 android 自动从该文件夹中选择它时要小。我能做些什么来解决这个问题?