标签:
1 package com.view.photo.demo; 2 3 import android.graphics.Bitmap; 4 import android.os.Bundle; 5 import android.os.Environment; 6 import android.support.v7.app.AppCompatActivity; 7 import android.util.Log; 8 import android.view.View; 9 import android.widget.TextView; 10 import java.io.File; 11 import java.io.FileOutputStream; 12 import java.text.SimpleDateFormat; 13 import java.util.Date; 15 16 public class MainActivity extends AppCompatActivity { 18 private TextView txtName2 = null; 19 private String PathUrl = Environment.getExternalStorageDirectory() + "/androidsj/"; 20 22 private void changeImage() { 23 //将布局转换为View类型对象 24 View view = getLayoutInflater().inflate(R.layout.activity_main, null); 25 26 txtName2 = (TextView) view.findViewById(R.id.txtName2); 27 txtName2.setText("肯德基,去你大爷22"); 28 29 //打开图像缓存 30 view.setDrawingCacheEnabled(true); 31 //必须调用measure和layout方法才能成功保存可视组件的截图到png图像文件 32 //测量View大小 33 view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), 34 View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); 35 //发送位置和尺寸到View及其所有的子View 36 view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); 37 38 try { 39 File file = new File(PathUrl); 40 if (!file.exists()) { 41 file.mkdirs(); 42 } 43 44 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); 45 String time = dateFormat.format(new Date()); 46 47 String BaoBaoUrl = PathUrl + time + ".png"; 48 File files = new File(BaoBaoUrl); 49 50 //获得可视组件的截图 51 Bitmap bitmap = view.getDrawingCache(); 52 //将截图保存在SD卡根目录的test.png图像文件中 53 FileOutputStream fos = new FileOutputStream(files); 54 //将Bitmap对象中的图像数据压缩成png格式的图像数据,并将这些数据保存在test.png文件中 55 bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); 56 //关闭文件输出流 57 fos.close(); 58 59 } catch (Exception e) { 60 Log.i("TAG", "changeImage肿么办...." + e.getMessage()); 61 } 62 } 64 65 @Override 66 protected void onCreate(Bundle savedInstanceState) { 67 super.onCreate(savedInstanceState); 68 69 changeImage(); 70 } 71 }
标签:
原文地址:http://www.cnblogs.com/androidsj/p/5714336.html