android截屏功能實(shí)現(xiàn)代碼
android開發(fā)中通過View的getDrawingCache方法可以達(dá)到截屏的目的,只是缺少狀態(tài)欄!
原始界面
截屏得到的圖片
代碼實(shí)現(xiàn)
1. 添加權(quán)限(AndroidManifest.xml文件里)
2. 添加1個(gè)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. 實(shí)現(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)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android開發(fā)實(shí)現(xiàn)繪制淘寶收益圖折線效果示例
這篇文章主要介紹了Android開發(fā)實(shí)現(xiàn)繪制淘寶收益圖折線效果,涉及Android canvas圖形繪制及布局控制相關(guān)操作技巧,需要的朋友可以參考下2017-11-11Android中的腦殘?jiān)O(shè)計(jì)總結(jié)
本篇文章是對(duì)Android中的腦殘?jiān)O(shè)計(jì)進(jìn)行了分析與介紹,需要的朋友參考下2013-05-05Android電量優(yōu)化提高手機(jī)續(xù)航
這篇文章主要為大家介紹了Android電量優(yōu)化提高你的手機(jī)續(xù)航示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02Android編程實(shí)現(xiàn)支持拖動(dòng)改變位置的圖片中疊加文字功能示例
這篇文章主要介紹了Android編程實(shí)現(xiàn)支持拖動(dòng)改變位置的圖片中疊加文字功能,可實(shí)現(xiàn)Android圖片與文字動(dòng)態(tài)操作功能,涉及視圖及圖片動(dòng)態(tài)運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2017-01-01

在Android系統(tǒng)中使用gzip進(jìn)行數(shù)據(jù)傳遞實(shí)例代碼