android實現截屏功能

android實現截屏功能

該方法主要利用SDK提供的view.getDrawingCache()方法,主要步驟如下:

  • 設置view.setDrawingCacheEnabled(true)
  • 調用view.buildDrawingCache(true)
  • 生產bitmap:Bitmap b = Bitmap.createBitmap(v.getDrawingCache())
  • 最後再設置回去v.setDrawingCacheEnabled(false)

如圖:

頁面主要由3部分構成:

1.textView,顯示hello world
2.button,點擊截圖
1.imageView,用來顯示截下的圖片

這裏寫圖片描述

這裏寫圖片描述

上代碼:


@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        //activityMain是佈局文件根LinearLayout,將其傳入截屏方法中,將截取整個頁面
        activityMain =(LinearLayout)findViewById(R.id.activity_main);
        imageView = (ImageView) findViewById(R.id.image_view);
}

//button按鍵處理,按下執行截圖操作,並將截圖顯示在imageView中
public void onClick(View view){
       bitmap_view = takeScreenShotOfView(view);
       imageView.setImageBitmap(bitmap_view);

    }


public Bitmap takeScreenShotOfView(View v) {
        v.setDrawingCacheEnabled(true);
        v.buildDrawingCache(true);

        Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
        v.setDrawingCacheEnabled(false); // clear drawing cache
        return b;
    }

佈局文件比較簡單,這裏就不貼布局文件的代碼了,小小demo,沒有太注重代碼邏輯,如有問題,歡迎指正,謝謝!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章