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,用来显示截下的图片

android实现截屏功能_第1张图片

android实现截屏功能_第2张图片

上代码:


@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,没有太注重代码逻辑,如有问题,欢迎指正,谢谢!
如果各位有好的想法,欢迎关注我的公众号(程序员顺仔)或留言讨论~
android实现截屏功能_第3张图片

你可能感兴趣的:(android)