对于这种情况,我有一个非常好的方法,就像一个魅力。您只需要为您创建一个高清图像,然后方法就可以解决所有问题。
这是方法:
/**
* Get DRAWABLE with original size screen resolution independent
* @param is Input stream of the drawable
* @param fileName File name of the drawable
* @param density Density value of the drawable
* @param context Current application context
* @return Drawable rearranged with its original values for all
* different types of resolutions.
*/
public static Drawable getDrawable(InputStream is, String fileName, int density, Context context) {
Options opts = new BitmapFactory.Options();
opts.inDensity = density;
opts.inTargetDensity = context.getResources().getDisplayMetrics().densityDpi;
return Drawable.createFromResourceStream(context.getResources(), null, is, fileName, opts);
}
在这里,您必须为您的图像文件准备输入流,并在您的任何使用区域设置适合您的屏幕的密度。密度越小质量越低,通过改变数值来解决。以下是使用该方法的一些示例:
1) 从 assets 文件夹中打开一个资产:
getDrawable(assetManager.open("image.png"), "any_title", 250, context)
2)从drawables文件夹中打开一个drawable:首先,您必须为您的输入流提供此方法:a)方法:
/**
* Get InputStream from a drawable
* @param context Current application context
* @param drawableId Id of the file inside drawable folder
* @return InputStream of the given drawable
*/
public static ByteArrayInputStream getDrawableAsInputStream(Context context, int drawableId) {
Bitmap bitmap = ((BitmapDrawable)context.getResources().getDrawable(drawableId)).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] imageInByte = stream.toByteArray();
return new ByteArrayInputStream(imageInByte);
}
和用法: b) 用法:
getDrawable(getDrawableAsInputStream(getBaseContext(), R.drawable.a_drawable), "any_title", 250, context)
我希望它是有用的。