【发布时间】:2015-02-06 12:57:45
【问题描述】:
我必须在运行时更改 android 应用程序的背景图像。我从博客和谷歌搜索了解到,我无法在 tun 时间修改资产或 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;
}
【问题讨论】:
-
通常,设备自己决定选择哪一个。因此,如果您引用 drawables 文件夹,它将从正确的文件夹中获取正确的图片。您唯一需要做的就是在每个文件夹中设置相同的文件名。
-
感谢您的信息。我必须在运行时将图像存储在内部存储中并在运行时访问它。
-
那么问题是什么?看起来你有一个计划;将它们存储在运行时的某个位置(保留该位置),然后在运行时使用它们。看来你不需要任何帮助。
-
如果我将图像存储在内部存储的某个文件夹中,应用程序将如何选择正确的分辨率图像?
-
您使用什么方式存储图像?
标签: android