The first necessary step is to add the appropriate permission to your AndroidManifest.xml.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
The code, in one lump:
View rootView = childView.getRootView(); rootView.setDrawingCacheEnabled(true); Bitmap bitmap = rootView.getDrawingCache(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos); File file = new File(Environment.getExternalStoreDirectory() + "/my_cap.jpg"); try { file.createNewFile(); FileOutputStream fos = new FileOutputStream(file); fos.write(baos.toByteArray()); fos.close(); } catch(Exception e) { e.printStackTrace(); }
Where childView is or inherits from the View class.
Hopefully you can extrapolate from line 6 and the usage of an enum that formats other than JPEG exist and this is merely what I chose for this example code. Likewise 80 is a value I decided on and is the desired quality of the output image; Only values from 0-100 are accepted. (Even though png files ignore this value it is still necessary to include one and that its value falls within the 0-100 range)