–Bitmap代表这一张位图,BitmapDrawable里封装的图片就是一个Bitmap对象。如果要将Bitmap对象封装成BitmapDrawable对象只需要用构造方法即可。
//讲bitmap对象包装成BitmapDrawable对象
BitmapDrawable drawable = new BitmapDrawable(bitmap);
//将BitmapDrawable对象转换为bitmap
Bitmap bitmap = drawable.getBitmap();
Bitmap对象提供了一系列静态方法来创建新的Bitmap对象
•createBitmap(Bitmap source, int x, int y, int width, int height):从原位图中指定坐标点(x,y)开始,从中挖取宽width、高height的一块出来,创建新的Bitmap对象。
•createScaledBitmap(Bitmap source, int dstWidth, int dstHeight, boolean filter):对源位图进行缩放,缩放成指定width、height大小的新位图对象。
•createBitmap(int width, int height, Bitmap.Config config):创建一个宽width、高height的新位图。
•createBitmap(Bitmap source, int x, int y, int width, int height, Matrix matrix, boolean filter):从原位图中指定坐标点(x,y)开始,从中挖取宽width、高height的一块出来,创建新的Bitmap对象。并按Matrix指定的规则进行变换。
BitmapFactory是一个工具类,它提供了大量的方法来用于从不同的数据源来解析、创建Bitmap对象。包含了如下方法
•decodeByteArray(byte[] data, int offset, int length):从指定的字节数组的offset位置开始,将长度为length的字节数据解析成Bitmap对象。
•decodeFile(String pathName):从pathName指定的文件中解析、创建Bitmap对象。
•decodeFileDescriptor(FileDescriptor fd):从FileDescriptor对应的文件中解析、创建Bitmap对象。
•decodeResource(Resources res, int id):根据给定的资源ID从指定资源中解析、创建Bitmap对象。
•decodeStream(InputStream is):从指定的输入流中解析、创建Bitmap对象。
如:
获取本地图片创建bitmap:
bmp=BitmapFactory.decodeResource(this.getResources(),R.drawable.haha);
当然可以获取网络图片创建bitmap:
URL conurl = new URL(url);
HttpURLConnection con = (HttpURLConnection) conurl.openConnection();
bmp = BitmapFactory.decodeStream(con.getInputStream());
此外附加学习:
android 获取资源文件 r.drawable中的图片转换为drawable、bitmap
1、
Resources resources = mContext.getResources();
Drawable drawable = resources.getDrawable(R.drawable.a);
imageview.setBackground(drawable);
2、
Resources r = this.getContext().getResources();
Inputstream is = r.openRawResource(R.drawable.my_background_image);
BitmapDrawable bmpDraw = new BitmapDrawable(is);
Bitmap bmp = bmpDraw.getBitmap();
3、
Bitmap bmp=BitmapFactory.decodeResource(r, R.drawable.icon);
Bitmap newb = Bitmap.createBitmap( 300, 300, Config.ARGB_8888 );
4、
InputStream is = getResources().openRawResource(R.drawable.icon);
Bitmap mBitmap = BitmapFactory.decodeStream(is);