您的位置:首页 > 移动开发 > Android开发

关于 Android 中的 getResource()

2015-12-09 21:21 447 查看
没办法 又遇到问题了

心中抑郁难解

发现写 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 dataid The resource id of the image dataReturns: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;

}

个人理解 如有不对 还望指出 谢谢~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: