Resource,Drawable和Bitmap之间的转换

来源:互联网 发布:大智慧分析家软件 编辑:程序博客网 时间:2024/06/06 12:47

一直接触这些东西,还是归个类整理一下比较好。


Resource -> Drawable

[javascript] view plaincopy
  1. Drawable draw1 = this.getResources().getDrawable(R.drawable.icon);  

Drawable -> Bitmap

1.

[javascript] view plaincopy
  1. static Bitmap drawableToBitmap(Drawable drawable) // drawable 转换成bitmap    
  2. {    
  3.     int width = drawable.getIntrinsicWidth();// 取drawable的长宽    
  4.     int height = drawable.getIntrinsicHeight();    
  5.     Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ?Bitmap.Config.ARGB_8888:Bitmap.Config.RGB_565;// 取drawable的颜色格式    
  6.     Bitmap bitmap = Bitmap.createBitmap(width, height, config);// 建立对应bitmap    
  7.     Canvas canvas = new Canvas(bitmap);// 建立对应bitmap的画布    
  8.     drawable.setBounds(0, 0, width, height);    
  9.     drawable.draw(canvas);// 把drawable内容画到画布中    
  10.     return bitmap;    
  11. }    
2.

[javascript] view plaincopy
  1. Bitmap bitmap = ((android.graphics.drawable.BitmapDraable) pm.getApplicationIcon(appInfo)).getBitmap();