gpt4 book ai didi

android - 从路径创建 BitmapDrawable

转载 作者:行者123 更新时间:2023-11-29 15:27:46 26 4
gpt4 key购买 nike

我正在尝试创建位图

 BitmapDrawable img = new BitmapDrawable(getResources(), "res/drawable/wrench.png");
Bitmap wrench = img.getBitmap();
//Bitmap wrench = BitmapFactory.decodeResource(getResources(), R.drawable.wrench);
canvas.drawColor(Color .BLACK);
Log.d("OLOLOLO",Integer.toString(wrench.getHeight()));
canvas.drawBitmap(wrench, left, top, null);

但是当我调用 wrench.getHeight() 时,程序因 NullPoinerException 而失败。 (我把文件放在drawable目录下)我该如何解决我的问题?

最佳答案

好的...我想我现在可以解决您的问题了。就像我说的,你不能通过路径访问你的可绘制对象,所以如果你想要一个可以通过编程方式构建的可绘制对象的人类可读界面,请在你的类中的某个地方声明一个 HashMap :

private static HashMap<String, Integer> images = null;

然后在你的构造函数中初始化它:

public myClass() {
if (images == null) {
images = new HashMap<String, Integer>();
images.put("Human1Arm", R.drawable.human_one_arm);
// for all your images - don't worry, this is really fast and will only happen once
}
}

现在访问 -

String drawable = "wrench";
// fill in this value however you want, but in the end you want Human1Arm etc
// access is fast and easy:
Bitmap wrench = BitmapFactory.decodeResource(getResources(), images.get(drawable));
canvas.drawColor(Color .BLACK);
Log.d("OLOLOLO",Integer.toString(wrench.getHeight()));
canvas.drawBitmap(wrench, left, top, null);

关于android - 从路径创建 BitmapDrawable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10113067/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com