Android中的Bitmap和Drawable

来源:互联网 发布:淘宝天猫网优惠券 编辑:程序博客网 时间:2024/04/28 22:31

相关概念

Drawable:一个可画的对象,可能是一张位图(BitmapDrawable),也可能是一个图形(ShapeDrawable)

CanVas画布:绘图的目的区域,用于绘图

Bitmap位图:用于图的处理

Matrix矩阵


从资源中获取Bitmap

Resources res = getResources();Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.icon);

Bitmap转化bytes[]

public byte[] Bitmap2Bytes(Bitmap bm) {ByteArrayOutputStream baos = new ByteArrayOutputStream();bm.compress(Bitmap.CompressFormat.PNG, 100, baos);return baos.toByteArray();}

byte[]转化Bitmap

public Bitmap Bytes2Bimap(byte[] b) {if (b.length != 0) {return BitmapFactory.decodeByteArray(b, 0, b.length);} else {return null;}}


Bitmap缩放

public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {int w = bitmap.getWidth();int h = bitmap.getHeight();Matrix matrix = new Matrix();float scaleWidth = ((float) width / w);float scaleHeight = ((float) height / h);matrix.postScale(scaleWidth, scaleHeight);Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);return newbmp;}

Drawable转化Bitmap

public static Bitmap drawableToBitmap(Drawable drawable) {// 取 drawable 的长宽int w = drawable.getIntrinsicWidth();int h = drawable.getIntrinsicHeight();// 取 drawable 的颜色格式Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888: Bitmap.Config.RGB_565;// 建立对应 bitmapBitmap bitmap = Bitmap.createBitmap(w, h, config);// 建立对应 bitmap 的画布Canvas canvas = new Canvas(bitmap);drawable.setBounds(0, 0, w, h);// 把 drawable 内容画到画布中drawable.draw(canvas);return bitmap;}



0 0
原创粉丝点击