1. 程式人生 > >android實現截圖功能程式碼

android實現截圖功能程式碼

android開發中通過View的getDrawingCache方法可以達到截圖的目的,只是缺少狀態列!

APP原始介面
這裡寫圖片描述

儲存截圖的檔案
這裡寫圖片描述

程式碼的實現
1. 新增許可權(AndroidManifest.xml檔案裡)

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

2.新增1個Button(activity_main.xml檔案)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/button" android:onClick="button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world"
/> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/button" android:layout_below="@+id/button" android:layout_marginTop="60dp" android:text="TextView" /> </RelativeLayout>

3.實現截圖(MainActivity.java檔案)

package com.texst.lp;

import java.io.File;
import java.io.FileOutputStream;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private TextView mTextView;
    private String filePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 圖片儲存路徑
        mTextView = (TextView) findViewById(R.id.textView1);
    }

    public void button(View view) {
        screenshot();
        mTextView.setText(filePath);
        Toast.makeText(getApplicationContext(), "jietu", Toast.LENGTH_SHORT)
                .show();
    }

    private void screenshot() {
        // 獲取螢幕
        View dView = getWindow().getDecorView();
        dView.setDrawingCacheEnabled(true);
        dView.buildDrawingCache();
        Bitmap bmp = dView.getDrawingCache();
        if (bmp != null) {
            try {
                // 獲取內建SD卡路徑
                String sdCardPath = Environment.getExternalStorageDirectory()
                        .getPath();
                // 圖片檔案路徑
                filePath = sdCardPath + File.separator + "screenshot.png";
                File file = new File(filePath);
                FileOutputStream os = new FileOutputStream(file);
                bmp.compress(Bitmap.CompressFormat.PNG, 100, os);
                os.flush();
                os.close();
            } catch (Exception e) {
            }
        }
    }

}