关于 Android 中的 getResource()

本文详细解析了在Android开发中如何使用BitmapFactory.decodeResource方法加载图片资源,并深入探讨了getResources()方法与系统资源ID之间的联系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

没办法 又遇到问题了

心中抑郁难解

发现写 blog 有舒缓内心抑郁之功效

写了两三行废话 果然有效

哈哈


好吧  转入正题

事情是这样的

看代码 看不嘛。。。


 //将图片转化为位图
Bitmap bitmap1=BitmapFactory.decodeResource(getResources(), R.drawable.erweima);

这句话中的 getResources() 获取应用中的图片对象不理解

换句话说 就是不知道怎么实现的。。。

等我想到了 就上来更文

先留个疑问吧 么么哒


/////////////////////////////////////////////////////////////////////////////////////////////

个人理解

/////////////////////////////////////////////////////////////////////////////////////////////


其实 博主不理解的是 

为什么 getResources() 可以和 R.drawable.erweima 这个系统资源 通过 decodeResource() 这个方法联系在一起


博主尝试翻底层源码。。。原谅一脸菜比色的博主

终于找到了 博主认为合理的解释

下面上菜


首先查阅 API 知道 getResources() 这个方法是用来 Return a Resources instance for your application's package.

返回你应用程序的实例的


接下来 查 decodeResource() 返回一个解码后的 bitmap 或者 null 值

Parameters:
res The resources object containing the image data
id The resource id of the image data
Returns:
The decoded bitmap, or null if the image could not be decode.

然后 这时候高潮来了

这个 getResources() 是如何获得 resources object containing the image data?

我们查看源码 黑粗斜 是代码流程 
红粗斜 是 getResource() 和 系统资源 id 联系起来的关键
写成这样好理解一些
is = getResource().openRawResource(id,value);
这样 就可以通过 getResource() 方法来获取对应 id 的实力了
然后 decodeResource() 就可以 return bm;
打完收工 

 public static Bitmap decodeResource(Resources res, int id) {
        return decodeResource(res, id, null);
    }

    public static Bitmap decodeResource(Resources res, int id, Options opts) {
        Bitmap bm = null;
        InputStream is = null; 
        
        try {
            final TypedValue value = new TypedValue();
            is = res.openRawResource(id, value);


            bm = decodeResourceStream(res, value, is, null, opts);
        } catch (Exception e) {
            /*  do nothing.
                If the exception happened on open, bm will be null.
                If it happened on close, bm is still valid.
            */
        } finally {
            try {
                if (is != null) is.close();
            } catch (IOException e) {
                // Ignore
            }
        }


        if (bm == null && opts != null && opts.inBitmap != null) {
            throw new IllegalArgumentException("Problem decoding into existing bitmap");
        }


        return bm;
    }

个人理解 如有不对 还望指出 谢谢~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值