將drawable下的圖片轉換成bitmap
1、 Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.xxx); 2、Resources r = this.getContext().getResources(); Inputstream is = r.openRawResource(R.drawable.xxx); BitmapDrawable bmpDraw = new BitmapDrawable(is); Bitmap bmp = bmpDraw.getBitmap(); 3、Resources r = this.getContext().getResources(); Bitmap bmp=BitmapFactory.decodeResource(r, R.drawable.icon); Bitmap bmp = Bitmap.createBitmap( 300, 300, Config.ARGB_8888 );
將drawable下的圖片轉換成Drawable
Resources resources = mContext.getResources(); Drawable drawable = resources.getDrawable(R.drawable.a); imageview.setBackground(drawable);
BitmapFactory.decodeResource為null的處理方法之一
問題代碼:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.danger_build10);
其中R.drawable.danger_build10是一個vector圖片,此代碼在4.4上運行正常,但在5.0以上的系統會出現空指針,原因在於此本來方法不能將vector轉化為bitmap,而apk編譯時為了向下兼容,會根據vector生產相應的png,而4.4的系統運行此代碼時其實用的是png資源。這就是為什么5.0以上會報錯,而4.4不會的原因
下面是解決辦法
private static Bitmap getBitmap(Context context,int vectorDrawableId) { Bitmap bitmap=null; if (Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP){ Drawable vectorDrawable = context.getDrawable(vectorDrawableId); bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); vectorDrawable.draw(canvas); }else { bitmap = BitmapFactory.decodeResource(context.getResources(), vectorDrawableId); } return bitmap; }
https://blog.csdn.net/zhw0596/article/details/80973246