分享一个简单的截屏代码。
1.主Activity
- package com.zhf.ScreenshotDemo;
-
- import Android.app.Activity;
- import android.graphics.Bitmap;
- import android.graphics.drawable.BitmapDrawable;
- import android.os.Bundle;
- import android.view.Display;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.ImageView;
-
- public class ScreenshotDemoActivity extends Activity {
- private Button shotButton;
- private ImageView imageView;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- shotButton=(Button)findViewById(R.id.shotButton);
- imageView=(ImageView)findViewById(R.id.imageView);
- shotButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
-
- BitmapDrawable bd=new BitmapDrawable(shot());
- imageView.setBackgroundDrawable(bd);
-
- }
- });
- }
-
-
-
-
-
- private Bitmap shot() {
- View view = getWindow().getDecorView();
- Display display = this.getWindowManager().getDefaultDisplay();
- view.layout(0, 0, display.getWidth(), display.getHeight());
- view.setDrawingCacheEnabled(true);
- Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache());
- return bmp;
- }
- }
|
2.布局
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
- <ImageView android:id="@+id/imageView"
- android:layout_width="fill_parent"
- android:layout_height="350dip"
- />
-
- <Button android:id="@+id/shotButton"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="shot"/>
- </LinearLayout>
1. 截屏函数似乎应该在onCreate方法之后调用,否则截取不到
2. 截取的图片比屏幕要小,看起来像是少了一个标题栏的高度