我正在开发一款包含许多图片的应用。由于app限制(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从该文件夹中自动选择它时要小。我该怎么做才能解决这个问题?