手抄报 安全手抄报 手抄报内容 手抄报图片 英语手抄报 清明节手抄报 节约用水手抄报

Android截屏代码经验

时间:2024-11-02 02:52:45

1、添加需要截屏的界面布局

2、<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="com.yacheng.slidedemo.MainActivity" > <ImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_height="match_parent" android:contentDescription="@null" android:src="@drawable/one" /> <Button android:id="@+id/nextPic" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_margin="10dp" android:background="@color/abc_search_url_text_normal" android:text="截屏" /></RelativeLayout>

Android截屏代码经验

3、主界面代码

4、/*** 截屏功能* @author Administrator**/public class 蘅荫酸圉GetFullScreemActivity extends Activity { static ByteArrayOutputStream baos = null; static Bitmap bitmap = null; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.nextPic).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { captureScreen(); } }); } private void captureScreen() { /** process screen capture on background thread */ Runnable action = new Runnable() { @Override public void run() { /** * activity's root layout id, you can change the * android.R.id.content to your root layout id */ final View contentView = findViewById(android.R.id.content); try { bitmap = Bitmap.createBitmap(contentView.getWidth(), contentView.getHeight(), Bitmap.Config.ARGB_4444); // bitmap = BMapUtil.getBitmapFromViews(contentView); contentView.draw(new Canvas(bitmap)); baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); savePic(bitmap,"sdcard/short.png"); } catch (Exception e) { e.printStackTrace(); } finally { try { /** no need to close, actually do nothing */ if (null != baos) baos.close(); if (null != bitmap && !bitmap.isRecycled()) { // bitmap.recycle(); bitmap = null; } } catch (IOException e) { e.printStackTrace(); } } } }; try { action.run(); } catch (Exception e) { e.printStackTrace(); } } /*** * 保存到sdcard * @param Bitmap b * @param String strFileName 保存地址 */ private void savePic(Bitmap b, String strFileName) { FileOutputStream fos = null; try { fos = new FileOutputStream(strFileName); if (null != fos) { boolean success= b.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.flush(); fos.close(); if(success) Toast.makeText(GetFullScreemActivity.this, "截屏成功", Toast.LENGTH_SHORT).show(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}

5、只配置文件需加入权限<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

6、点击截屏按钮后,可在文件管理器中查到截取的屏幕图片测试成功:

Android截屏代码经验
© 手抄报圈