[英]Is it possible to load a drawable from the assets folder?
您可以从assets
(不是可绘制文件夹)文件夹中的子目录加载可绘制对象吗?
希望这有帮助:
Drawable d = Drawable.createFromStream(getAssets().open("Cloths/btn_no.png"), null);
我建议使用这个
Drawable.createFromResourceStream(resources,new TypedValue(), resources.getAssets().open(filename), null)
由于资源,它返回适当缩放的可绘制对象......
这是一个带有静态方法的类,用于从资产中获取可绘制对象。 它还关闭输入流。
import android.content.Context;
import android.graphics.drawable.Drawable;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by bartburg on 4-11-2015.
*/
public class AssetsReader {
public static Drawable getDrawableFromAssets(Context context, String url){
Drawable drawable = null;
InputStream inputStream = null;
try {
inputStream = context.getAssets().open(url);
drawable = Drawable.createFromStream(inputStream, null);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return drawable;
}
}
这是为您执行此操作的功能。
检查返回的 Drawable 变量是否为 null,因为如果路径无效或存在 IOException,则可能返回 null。
public static Drawable getDrawableFromAssetFolder(String fullPath, Activity ctx) {
Drawable d =null;
try {
d = Drawable.createFromStream(ctx.getAssets().open(fullPath), null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return d;
}
是的,您可以使用createFromStream()方法从InputStream
创建一个Drawable
对象。
这有助于获得正确的密度
private Drawable drawableFromAssetFilename(String filename) {
AssetManager assetManager = mApplicationContext.getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open(filename);
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
BitmapDrawable drawable = new BitmapDrawable(mApplicationContext.getResources(), bitmap);
return drawable;
}
我在 RecyclerView 适配器中工作,发现David 的回答对我不起作用,(由于某种原因,无论我导入什么, asset.open
仍然未解决)
所以我发现这对我有用(Kotlin 代码)
val d = Drawable.createFromStream(context?.assets?.open("imageData/${imageName}.png"), null)
这是我的目录,您可以看到资产从资产文件夹开始,这里是有关如何创建该资产文件夹的链接
在这个版本你不能,如果你在你的 drawable 文件夹中创建一个子文件夹你不能在你的 xml 文件中使用它,当你使用 android:src 时它不会被识别。
看看这个线程: Android drawable 目录可以包含子目录吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.