Package Zhangphil.viewtoimage;import Java.io.file;import Java.io.fileoutputstream;import android.os.Bundle;import Android.os.environment;import Android.os.handler;import Android.view.view;import Android.widget.Button;import Android.widget.textview;import Android.app.activity;import Android.graphics.bitmap;import Android.graphics.Canvas ; Import Android.graphics.color;import android.graphics.paint;/** * Convert a view from Android to a picture save * * */public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.activity_main); final TextView TV = (TextView) Findviewbyid ( R.id.textview); Tv.setbackgroundcolor (color.green);//tv.setdrawingcacheenabled (TRUE); final Runnable Runnable = new Runnable () {@Overridepublic void run () {viewsavetoimage (TV);}}; Button button = (button) Findviewbyid (R.id.button); Button.setonclicklistener (new View.onclicklistener () {@ overridepublic void OnClick (View v) {new Handler (). Post (runnable);}});} public void Viewsavetoimage (view view) {view.setdrawingcacheenabled (true); View.setdrawingcachequality (view.drawing _cache_quality_high); View.setdrawingcachebackgroundcolor (color.white);//Convert a view to a picture bitmap cachebmp = Loadbitmapfromview (view);//Add watermark Bitmap bitmap = Bitmap.createbitmap (Createwatermarkbitmap (Cachebmp, "@ Zhang Phil")); FileOutputStream Fos;try {//Determine if the phone device has an SD card Boolean ishassdcard = Environment.getexternalstoragestate (). Equals ( Android.os.Environment.MEDIA_MOUNTED); if (Ishassdcard) {///SD card root directory file Sdroot = Environment.getexternalstoragedirectory (); File File = new file (sdroot, "test. PNG "); fos = new FileOutputStream (file);} Elsethrow New Exception ("Failed to create file!"); Bitmap.compress (Bitmap.CompressFormat.PNG, N, Fos); Fos.flush (); Fos.close (); catch (Exception e) {e.printstacktrace ();} View.destroydrawingcache ();} Private Bitmap Loadbitmapfromview (View v) {int w = v.getwidth (); int h = v.getheight (); Bitmap bmp = Bitmap.createbitmap (W, H, Bitmap.Config.ARGB_8888); Canvas C = new CaNvas (BMP); C.drawcolor (color.white);/** if the canvas canvas is not set to white, a transparent */v.layout (0, 0, W, h) is generated, V.draw (c); return bmp;} Add a watermark to the image target private Bitmap createwatermarkbitmap (Bitmap target, String str) {int w = target.getwidth (); int h = target. GetHeight (); Bitmap bmp = Bitmap.createbitmap (W, H, Bitmap.Config.ARGB_8888); Canvas canvas = new canvas (BMP); Paint p = new paint ();//Watermark Color P.setcolor (color.red);//Watermark Font size p.settextsize (;p). Setantialias (True); Anti-aliasing Canvas.drawbitmap (target, 0, 0, p);//Start adding watermarks canvas.drawtext (str, W/2, H/2, p) in the middle position canvas.save (canvas.all_save_fla G); Canvas.restore (); return bmp;}}
Android view Convert to picture save