Android 位图语法
我想将位图加载到 Android 中的 ImageView 中,但我不想使用 R.drawable 语法,因为我有很多具有标准命名约定的图像,因此通过一些逻辑获取图像要容易得多。例如,我所有的图像都命名为:
img1.png img2.png img3.png
因此,如果用户选择一个值(假设为 x),我会在 ImageView 中显示“img”+x+“.png”。看起来 Bitmap.decodeFile 是我需要的,但我需要知道如何访问我的可绘制文件夹的语法,因为那是图像所在的位置。或者是否有更好的方法。
我意识到我可以使用 switch 语句来完成此操作,而不是连接图像名称,但这会需要很多行,因为我有很多图像。
I want to load bitmaps into ImageViews in Android, but I don't want to use the R.drawable syntax because I have a lot of images with a standard naming convention so it's much easier to get the image with some logic. For example, all my images are named:
img1.png
img2.png
img3.png
So if a user selects a value, let's say x, I show "img" + x + ".png" in the ImageView. Looks like Bitmap.decodeFile is what I need, but I need to know the syntax of how to get to my drawables folder since that's where the images are. Or if there's perhaps a better way.
I realize I could do this with a switch statement instead of concatenating the image name but that would be a lot of lines since I have so many images.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一种替代方法是使用反射从 R 加载图像。您可以通过字符串名称查找静态变量。但请记住,反思可能会很慢。如果您要多次加载同一张图像,您可能需要保留名称 -> 的缓存。里德。
编辑:
您还可以通过 URI 访问它们。请参阅使用 uri 引用 Android 资源。
One alternative is to use reflection to load images from R. You can looking static variables by string name. Keep in mind that reflection can be slow though. If you are going to be loading the same image multiple times, you might want to keep a cache of name -> R id.
Edit:
You can also access them by URI. See referring to android resources using uris.
R.drawable 值本身就是一个数字。您只需使用第一个图像 ID 并添加固定值即可找到正确的图像。例如:
R.drawable.image1 = 1234;
R.drawable.image2 = 1235;
等等。
因此,要获得图像 2,我会使用 R.drawable.image1 + 1。
每次重新生成 R.java 文件时,数字可能会发生变化,但序列是相同的。如果您不想依赖于此,那么您将不得不查看“assets”文件夹。
The R.drawable value is a number by itself. You just need to use the first image id and add a fixed value to find the right image. For example:
R.drawable.image1 = 1234;
R.drawable.image2 = 1235;
etc.
So to get image 2 I would to R.drawable.image1 + 1.
Every time the R.java file is regenerated the numbers may change but the sequence will be the same. If you don't want to depend in this then you will have to look at the "assets" folder.
看来我找到了解决办法。真正的问题是我在运行时生成资源名称,但我可以像这样获取资源 id:
getResources().getIdentifier("string1" + string2, "id", "com.company.package")
然后我可以将该值传递给 setImageResource 或任何其他接受资源 id 的方法。
Looks like I've found a solution. The real problem is that I generate the resource names at runtime, but I can get the resource id like this:
getResources().getIdentifier("string1" + string2, "id", "com.company.package")
I can then pass that value to setImageResource or any other method that accepts a resource id.