我想將某個Drawable
設置爲設備的牆紙,可是全部牆紙功能僅接受Bitmap
。 個人2.1版以前沒法使用WallpaperManager
。 canvas
另外,個人可繪製對象是從Web下載的,並不位於R.drawable
。 spa
public static Bitmap drawableToBitmap (Drawable drawable) { Bitmap bitmap = null; if (drawable instanceof BitmapDrawable) { BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; if(bitmapDrawable.getBitmap() != null) { return bitmapDrawable.getBitmap(); } } if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) { bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel } else { bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; }
// get image path from gallery protected void onActivityResult(int requestCode, int resultcode, Intent intent) { super.onActivityResult(requestCode, resultcode, intent); if (requestCode == 1) { if (intent != null && resultcode == RESULT_OK) { Uri selectedImage = intent.getData(); String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); filePath = cursor.getString(columnIndex); //display image using BitmapFactory cursor.close(); bmp = BitmapFactory.decodeFile(filepath); iv.setBackgroundResource(0); iv.setImageBitmap(bmp); } } }
很簡單code
Bitmap tempBMP = BitmapFactory.decodeResource(getResources(),R.drawable.image);
這是更好的分辨率 對象
public static Bitmap drawableToBitmap (Drawable drawable) { if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable)drawable).getBitmap(); } Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } public static InputStream bitmapToInputStream(Bitmap bitmap) { int size = bitmap.getHeight() * bitmap.getRowBytes(); ByteBuffer buffer = ByteBuffer.allocate(size); bitmap.copyPixelsToBuffer(buffer); return new ByteArrayInputStream(buffer.array()); }
Android提供了一種非直接的解決方案: BitmapDrawable
。 要得到位圖,咱們必須將資源ID R.drawable.flower_pic
提供給BitmapDrawable
,而後將其轉換爲Bitmap
。 get
Bitmap bm = ((BitmapDrawable) getResources().getDrawable(R.drawable.flower_pic)).getBitmap();