android实现截屏功能代码
发布时间:2020-12-14 23:51:30 所属栏目:Java 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" / 2. 添加1个Button(activity_main.xml文件) RelativeLayout xmlns:an
以下代码由PHP站长网 52php.cn收集自互联网 现在PHP站长网小编把它分享给大家,仅供参考 <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" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/hello_world" /> <Button android:id="@+id/btn_save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Screenshot" /> </RelativeLayout>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); bmp.compress(Bitmap.CompressFormat.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; } } 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究 如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |