【发布时间】:2019-10-31 03:45:47
【问题描述】:
我想从类中的函数返回一个位图,大多数时候我会返回一个生成的图像,这很好,但在某些情况下我想从资源中返回文件。
This answer 到BitmapFactory.decodeResource and drawable* folders 问题告诉我使用
Resources res = getContext().getResources();
int id = R.drawable.image;
Bitmap b = BitmapFactory.decodeResource(res, id);
我翻译成的
val res = getContext().getResources()
val errorbitmap:Bitmap = BitmapFactory.decodeResource( res, R.drawable.pm5544)
但当然有编译错误:
未解决的参考:getContext
这引出了我的问题:
-
我需要在什么对象上调用
getContext()? 或解决真正的问题: - 我应该使用其他 API 来从我的资源中获取位图吗?
【问题讨论】:
-
尝试使用资源 res = getResources();或资源 res = getApplicationContext().getResources();
-
显然我的班级都看不到这些
-
您可以发布您的活动代码吗?
-
那将是我无法分享的大部分无关代码,但我的主要活动是
class MainActivity : AppCompatActivity(),它将这个类创建为object: {...} -
为什么不简单地在参数中传递上下文?