在运行时访问不同设备上的正确图像资源

时间:2015-02-04 07:53:09

标签: android

我必须在运行时更改Android应用程序的背景图像。我从博客和谷歌搜索中了解到,我无法在修改时修改资产或res / drawable文件夹来存储图像。

所以我在运行时将图像存储在内部存储中以在android应用程序中显示为背景图像。但是如何在不同设备上访问正确的图像资源,编程方式类似于res \ drawable \ hdpi,res \ drawable \ mdpi等分辨率文件夹。

public String saveImageToInternalSorage(Context context, Resources resources)
{

    ContextWrapper cw = new ContextWrapper(context);
    // path to /data/data/[app name]/app_imageDir
    File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
    // Create imageDir
    File mypath;
    Bitmap bitmapImage;
    if (isLandscape()) {
        mypath = new File(directory, "bg_repository_menu_landscape.jpg");
        bitmapImage = BitmapFactory.decodeResource(resources, R.drawable.bg_repository_menu_landscape);
    }
    else {
        mypath = new File(directory, "bg_repository_menu_portrait.jpg");
        bitmapImage = BitmapFactory.decodeResource(resources, R.drawable.bg_repository_menu_portrait);
    }

    FileOutputStream fos = null;
    try {

        fos = new FileOutputStream(mypath);

        // Use the compress method on the BitMap object to write image to the OutputStream
        bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return directory.getAbsolutePath();
}


public Drawable loadImageFromInternalStorage(String path, Resources resources)
{
    //DisplayMetrics metrics = resources.getDisplayMetrics();
    //int densityDpi = (int) (metrics.density * 160f);
    File file;
    try {
        if (isLandscape()) {
            file = new File(path, "bg_repository_menu_landscape.jpg");
        }
        else {
            file = new File(path, "bg_repository_menu_portrait.jpg");
        }
        Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(file));

        // bitmap.setDensity(densityDpi);

        Drawable drawable = new BitmapDrawable(resources, bitmap);
        return drawable;
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

2 个答案:

答案 0 :(得分:1)

您可以使用以下方式访问设备的DPI:

int getDeviceDpi() {
    DisplayMetrics metrics = getResources().getDisplayMetrics();
    return densityDpi = (int)(metrics.density * 160f);
}

然后看看here来确定它是否是hdpi,ldpi等。

答案 1 :(得分:0)

if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
                // show image for landscape
                Log.d(TAG, "LANDSCAPE");
            }
            else {
                // show image for potrait
                Log.d(TAG, "PORTRAIT");
            }