下面提供几种将控件上的内容转成bitmap的方式,根据需要选用
一imageview 转bitmap Bitmap image = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
二 可以控制大小
private static Bitmap convertViewToBitmap(View view) { view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); view.buildDrawingCache(); Bitmap bitmap = view.getDrawingCache(); return bitmap; }
三 画布方式转换,测试没问题
private static Bitmap createViewBitmap(View v) { Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); v.draw(canvas); return bitmap; }附上将bitmap存到本地代码
private static String getSDPath() { boolean hasSDCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); if (hasSDCard) return Environment.getExternalStorageDirectory().toString() + "/aasaving_picture"; return null; } /** * 保存图片 * * @param strFileName */ public static void saveImage(String strFileName, View view, Context context) { if (getSDPath() == null) { Toast.makeText(context, "SD卡不存在", Toast.LENGTH_SHORT).show(); return; } Bitmap bitmap = createViewBitmap(view); if (bitmap == null) { Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show(); return; } String strPath = getSDPath(); try { File destDir = new File(strPath); if (!destDir.exists()) { Log.d("MagicMirror", "Dir not exist create it " + strPath); destDir.mkdirs(); Log.d("MagicMirror", "Make dir success: " + strPath); } File imageFile = new File(strPath + "/" + strFileName); imageFile.createNewFile(); FileOutputStream fos = new FileOutputStream(imageFile); bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos); fos.flush(); fos.close(); Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show(); } catch (IOException e) { // TODO Auto-generated catch block Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } }