亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

android截屏功能實現(xiàn)代碼

 更新時間:2021年07月11日 09:53:15   作者:fmp8  
這篇文章主要為大家詳細介紹了android截屏功能的實現(xiàn)代碼,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

android開發(fā)中通過View的getDrawingCache方法可以達到截屏的目的,只是缺少狀態(tài)欄!

原始界面

截屏得到的圖片

代碼實現(xiàn)

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"
  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. 實現(xiàn)截屏(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 {
     // 獲取內(nèi)置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;
 }

}

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論