將drawable下的圖片轉換成bitmapcanvas
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下的圖片轉換成Drawablemarkdown
Resources resources = mContext.getResources(); Drawable drawable = resources.getDrawable(R.drawable.a); imageview.setBackground(drawable);
BitmapFactory.decodeResource爲null的處理方法之一
問題代碼: ui
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不會的緣由this
下面是解決辦法spa
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.net