关于Bitmap图像资源的获取

来源:互联网 发布:pp苹果助手mac版 编辑:程序博客网 时间:2024/06/05 01:13

创建Bitmap对象有几种方法。下面简单列举两大类。
一,Bitmap对象提供了一系列静态方法来创建新的Bitmap对象。


1.createBitmap(Bitmap source, int x, int y, int width, int height):从原位图中指定坐标点(x,y)开始,从中挖取宽width、高height的一块出来,创建新的Bitmap对象。
2.createScaledBitmap(Bitmap source, int dstWidth, int dstHeight, boolean filter):对源位图进行缩放,缩放成指定width、height大小的新位图对象。
3.createBitmap(int width, int height, Bitmap.Config config):创建一个宽width、高height的新位图。
4.createBitmap(Bitmap source, int x, int y, int width, int height, Matrix matrix, boolean filter):从原位图中指定坐标点(x,y)开始,从中挖取宽width、高height的一块出来,创建新的Bitmap对象。并按Matrix指定的规则进行变换。


二、BitmapFactory是一个工具类,它提供了大量的方法来用于从不同的数据源来解析、创建Bitmap对象。包含了如下方法:


1.decodeByteArray(byte[] data, int offset, int length):从指定的字节数组的offset位置开始,将长度为length的字节数据解析成Bitmap对象。
2.decodeFile(String pathName):从pathName指定的文件中解析、创建Bitmap对象。
3.decodeFileDescriptor(FileDescriptor fd):从FileDescriptor对应的文件中解析、创建Bitmap对象。
4.decodeResource(Resources res, int id):根据给定的资源ID从指定资源中解析、创建Bitmap对象。
5.decodeStream(InputStream is):从指定的输入流中解析、创建Bitmap对象。
注意:
大部分时候我们只需把图片放在/res/drawable目录下就可以在程序中通过该图片的资源ID来获取封装的drawable对象。但由于手机系统的内存比较小,如果系统不停地去解析、创建Bitmap对象,可能由于前面的资源所占用的内存还没释放,从而导致内存溢出错误。
Adroid为Bitmap提供了两个方法来判断它是否已被回收,以及强制Bitmap回收自己。
boolean isRecycled():返回该对象是否已被回收。
void recycle():强制一个Bitmap对象立即回收自己。
除此之外,如果Android应用需要访问其他存储路径(比如SDCARD)里的图片,都需要借助BitmapFactory来解析、创建Bitmap对象。

原创粉丝点击