700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > android中截屏功能实现 android代码实现截屏功能

android中截屏功能实现 android代码实现截屏功能

时间:2023-05-06 16:01:32

相关推荐

android中截屏功能实现 android代码实现截屏功能

android开发中通过View的getDrawingCache方法可以达到截屏的目的,只是缺少状态栏!

原始界面

截屏得到的图片

代码实现

1. 添加权限(AndroidManifest.xml文件里)

2. 添加1个Button(activity_main.xml文件)

xmlns:tools="/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity" >

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_centerVertical="true"

android:text="@string/hello_world" />

android:id="@+id/btn_save"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Screenshot"

/>

3. 实现截屏(MainActivity.java文件)

package com.example.androidtest;

import java.io.File;

import java.io.FileOutputStream;

import android.os.Bundle;

import android.os.Environment;

import android.app.Activity;

import android.graphics.Bitmap;

import android.view.Menu;

import android.view.View;

import android.widget.Button;

public class MainActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button btn = (Button) this.findViewById(R.id.btn_save);

btn.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

screenshot();

}

});

}

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();

// 图片文件路径

String filePath = sdCardPath + File.separator + "screenshot.png";

File file = new File(filePath);

FileOutputStream os = new FileOutputStream(file);

press(pressFormat.PNG, 100, os);

os.flush();

os.close();

} catch (Exception e) {

}

}

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.activity_main, menu);

return true;

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。