实现功能
以当前时间命名图片名称,并保存到SD卡
缺陷
无法截到时间栏
代码如下
工具类Utils
import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Rect; import android.view.View; public class Utils { public static Bitmap windowShot(Activity activity) { // 需要截图的view View view = activity.getWindow().getDecorView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap bmp = view.getDrawingCache(); // 获取状态栏的高度 Rect frame = new Rect(); activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.top; // 获取屏幕的宽和高 int width = activity.getWindowManager().getDefaultDisplay().getWidth(); int height = activity.getWindowManager().getDefaultDisplay() .getHeight(); // 生成图片 Bitmap bp = null; bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height - statusBarHeight); view.destroyDrawingCache(); return bp; } }
实现类
import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import android.app.Activity; import android.graphics.Bitmap; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends Activity { private Button bt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bt = (Button) findViewById(R.id.bt); bt.setOnClickListener(new OnClickListener() { public void onClick(View v) { SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd_HH-mm-ss", Locale.US); String fname = "/sdcard/" + sdf.format(new Date()) + ".png"; View view = v.getRootView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap bitmap = Utils.windowShot(MainActivity.this); if (bitmap != null) { System.out.println("bitmap got!"); try { FileOutputStream out = new FileOutputStream(fname); bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); System.out.println("file " + fname + "output done."); } catch (Exception e) { e.printStackTrace(); } } else { System.out.println("bitmap is NULL!"); } } }); } }
因为要对SD卡进行操作,所以需要添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />