Java Android:拍摄一个视图的截图,保存图像并检索它

Java Android:拍摄一个视图的截图,保存图像并检索它,java,android,android-layout,android-studio,Java,Android,Android Layout,Android Studio,我基本上是在尝试捕获活动中相对布局的屏幕截图,并将其保存为PNG图像。然后我需要将其作为位图文件检索。我写了一些代码来完成这项工作,但遗憾的是屏幕截图没有保存在我的设备上 XML <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/paren

我基本上是在尝试捕获活动中相对布局的屏幕截图,并将其保存为PNG图像。然后我需要将其作为位图文件检索。我写了一些代码来完成这项工作,但遗憾的是屏幕截图没有保存在我的设备上

XML

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/parent"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Other views -->

</RelativeLayout>
上面的代码不起作用。没有错误,但未捕获和保存视图。有人能指出这个问题或给我一个更好的解决方案吗

  • 首先为相关视图指定一个id

  • 使用
    findViewById()
    然后按照下面的代码片段进行操作

  • //使用视图的高度和宽度定义位图

    Bitmap viewBitmap = Bitmap.createBitmap(v.getWidth(),v.getHeight(),Bitmap.Config.RGB_565);
    
    Canvas viewCanvas = new Canvas(viewBitmap);
    
    //get background of canvas
    Drawable backgroundDrawable = v.getBackground();
    
    if(backgroundDrawable!=null){
    backgroundDrawable.draw(viewCanvas);//draw the background on canvas;
    }
    else{
    viewCanvas.drawColor(Color.GREEN);
    //draw on canvas
    v.draw(viewCanvas) 
    }
    
    //write the above generated bitmap  to a file
    String fileStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            OutputStream outputStream = null;
            try{
                imgFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),fileStamp+".png");
                outputStream = new FileOutputStream(imgFile);
                b.compress(Bitmap.CompressFormat.PNG,40,outputStream);
                outputStream.close();
            }
            catch(Exception e){
                e.printStackTrace();
            }
    
    用JPEG替换PNG

    不要忘记添加此权限

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
    
    

    希望这有帮助:)

    有人可以编辑问题的代码部分吗?有一个bug,我似乎无法在中编辑code@Baronz谢谢你编辑这个问题,伙计
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>