51

最终更新

功能请求已由 Google 完成。请在下面查看此答案。

原始问题

使用旧版本的 Google Maps Android API,我能够捕获谷歌地图的屏幕截图以通过社交媒体分享。我使用以下代码捕获屏幕截图并将图像保存到文件中,效果很好:

public String captureScreen()
{
    String storageState = Environment.getExternalStorageState();
    Log.d("StorageState", "Storage state is: " + storageState);

    // image naming and path  to include sd card  appending name you choose for file
    String mPath = this.getFilesDir().getAbsolutePath();

    // create bitmap screen capture
    Bitmap bitmap;
    View v1 = this.mapView.getRootView();
    v1.setDrawingCacheEnabled(true);
    bitmap = Bitmap.createBitmap(v1.getDrawingCache());
    v1.setDrawingCacheEnabled(false);

    OutputStream fout = null;

    String filePath = System.currentTimeMillis() + ".jpeg";

    try 
    {
        fout = openFileOutput(filePath,
                MODE_WORLD_READABLE);

        // Write the string to the file
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
        fout.flush();
        fout.close();
    } 
    catch (FileNotFoundException e) 
    {
        // TODO Auto-generated catch block
        Log.d("ImageCapture", "FileNotFoundException");
        Log.d("ImageCapture", e.getMessage());
        filePath = "";
    } 
    catch (IOException e) 
    {
        // TODO Auto-generated catch block
        Log.d("ImageCapture", "IOException");
        Log.d("ImageCapture", e.getMessage());
        filePath = "";
    }

    return filePath;
}

但是,API V2 使用的新 GoogleMap 对象没有 MapView 那样的“getRootView()”方法。

我试图这样做:

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.basicMap);

    View v1 = mapFragment.getView();

但我得到的截图没有任何地图内容,看起来像这样: 空白地图截图

有人知道如何截取新的 Google Maps Android API V2 的屏幕截图吗?

更新

我也尝试通过这种方式获取 rootView:

View v1 = getWindow().getDecorView().getRootView();

这会生成一个屏幕截图,其中包含屏幕顶部的操作栏,但地图仍然是空白的,就像我附加的屏幕截图一样。

更新

已向 Google 提交功能请求。如果这是您希望谷歌在未来添加的内容,请在功能请求中添加星标: 向 Google Maps API V2 添加屏幕截图功能

4

9 回答 9

66

更新 - 谷歌添加了一个快照方法**!:

已满足对 Android Google Map API V2 OpenGL 层进行屏幕截图的方法的功能请求。

要截屏,只需实现以下接口:

public abstract void onSnapshotReady (Bitmap snapshot)

并致电:

public final void snapshot (GoogleMap.SnapshotReadyCallback callback)

截取屏幕截图,然后显示标准“图像共享”选项的示例:

public void captureScreen()
    {
        SnapshotReadyCallback callback = new SnapshotReadyCallback() 
        {

            @Override
            public void onSnapshotReady(Bitmap snapshot) 
            {
                // TODO Auto-generated method stub
                bitmap = snapshot;

                OutputStream fout = null;

                String filePath = System.currentTimeMillis() + ".jpeg";

                try 
                {
                    fout = openFileOutput(filePath,
                            MODE_WORLD_READABLE);

                    // Write the string to the file
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
                    fout.flush();
                    fout.close();
                } 
                catch (FileNotFoundException e) 
                {
                    // TODO Auto-generated catch block
                    Log.d("ImageCapture", "FileNotFoundException");
                    Log.d("ImageCapture", e.getMessage());
                    filePath = "";
                } 
                catch (IOException e) 
                {
                    // TODO Auto-generated catch block
                    Log.d("ImageCapture", "IOException");
                    Log.d("ImageCapture", e.getMessage());
                    filePath = "";
                }

                openShareImageDialog(filePath);
            }
        };

        mMap.snapshot(callback);
    }

图像完成捕获后,它将触发标准的“共享图像”对话框,以便用户可以选择他们想要共享的方式:

public void openShareImageDialog(String filePath) 
{
File file = this.getFileStreamPath(filePath);

if(!filePath.equals(""))
{
    final ContentValues values = new ContentValues(2);
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
    values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
    final Uri contentUriFile = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

    final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
    intent.setType("image/jpeg");
    intent.putExtra(android.content.Intent.EXTRA_STREAM, contentUriFile);
    startActivity(Intent.createChooser(intent, "Share Image"));
}
else
{
            //This is a custom class I use to show dialogs...simply replace this with whatever you want to show an error message, Toast, etc.
    DialogUtilities.showOkDialogWithText(this, R.string.shareImageFailed);
}
}

文档在这里

于 2013-08-07T01:41:45.637 回答
30

以下是通过示例捕获 Google Map V2 屏幕截图的步骤

步骤 1.打开Android Sdk Manager (Window > Android Sdk Manager)然后Expand Extras现在update/install Google Play Services to Revision 10忽略此步骤(如果已经)installed

在此处阅读注释https://developers.google.com/maps/documentation/android/releases#august_2013

第2步。 Restart Eclipse

步骤 3。 import com.google.android.gms.maps.GoogleMap.SnapshotReadyCallback;

步骤 4. 制作方法来捕获/存储地图的屏幕/图像,如下所示

public void CaptureMapScreen() 
{
SnapshotReadyCallback callback = new SnapshotReadyCallback() {
            Bitmap bitmap;

            @Override
            public void onSnapshotReady(Bitmap snapshot) {
                // TODO Auto-generated method stub
                bitmap = snapshot;
                try {
                    FileOutputStream out = new FileOutputStream("/mnt/sdcard/"
                        + "MyMapScreen" + System.currentTimeMillis()
                        + ".png");

                    // above "/mnt ..... png" => is a storage path (where image will be stored) + name of image you can customize as per your Requirement

                    bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        myMap.snapshot(callback);

        // myMap is object of GoogleMap +> GoogleMap myMap;
        // which is initialized in onCreate() => 
        // myMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_pass_home_call)).getMap();
}

第 5 步。CaptureMapScreen()现在在要捕获图像的位置调用此方法

就我而言,我calling this method on Button click in my onCreate()工作正常

像:

Button btnCap = (Button) findViewById(R.id.btnTakeScreenshot);
    btnCap.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            try {
                CaptureMapScreen();
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }

        }
    });

在这里这里检查文档

于 2013-08-19T07:34:43.300 回答
6

我捕获了地图截图。它会有所帮助

  private GoogleMap map;
 private static LatLng latLong;

`

public void onMapReady(GoogleMap googleMap) {
           map = googleMap;
           setMap(this.map);
           animateCamera();
            map.moveCamera (CameraUpdateFactory.newLatLng (latLong));
            map.setOnMapLoadedCallback (new GoogleMap.OnMapLoadedCallback () {
                @Override
                public void onMapLoaded() {
                    snapShot();
                }
            });
        }

`

snapShot() 方法用于截取地图

 public void snapShot(){
    GoogleMap.SnapshotReadyCallback callback=new GoogleMap.SnapshotReadyCallback () {
        Bitmap bitmap;
        @Override
        public void onSnapshotReady(Bitmap snapshot) {
            bitmap=snapshot;

            try{
                file=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"map.png");
                FileOutputStream fout=new FileOutputStream (file);
                bitmap.compress (Bitmap.CompressFormat.PNG,90,fout);
                Toast.makeText (PastValuations.this, "Capture", Toast.LENGTH_SHORT).show ();

            }catch (Exception e){
                e.printStackTrace ();
                Toast.makeText (PastValuations.this, "Not Capture", Toast.LENGTH_SHORT).show ();
            }


        }
    };map.snapshot (callback);
}

我的输出如下在此处输入图像描述

于 2018-08-08T14:35:09.617 回答
4

编辑:此答案不再有效 - Google Maps Android API V2 上的屏幕截图功能请求已得到满足。有关示例,请参见此答案

原始接受的答案

由于新的 Android API v2 地图使用 OpenGL 显示,因此无法创建屏幕截图。

于 2012-12-10T13:13:44.790 回答
4

由于投票最多的答案不适用于地图片段顶部的折线和其他叠加层(我在寻找什么),我想分享这个解决方案。

public void captureScreen()
        {
            GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback()
            {


                @Override
                public void onSnapshotReady(Bitmap snapshot) {
                    try {
                        getWindow().getDecorView().findViewById(android.R.id.content).setDrawingCacheEnabled(true);
                        Bitmap backBitmap = getWindow().getDecorView().findViewById(android.R.id.content).getDrawingCache();
                        Bitmap bmOverlay = Bitmap.createBitmap(
                                backBitmap.getWidth(), backBitmap.getHeight(),
                                backBitmap.getConfig());
                        Canvas canvas = new Canvas(bmOverlay);
                        canvas.drawBitmap(snapshot, new Matrix(), null);
                        canvas.drawBitmap(backBitmap, 0, 0, null);

                        OutputStream fout = null;

                        String filePath = System.currentTimeMillis() + ".jpeg";

                        try
                        {
                            fout = openFileOutput(filePath,
                                    MODE_WORLD_READABLE);

                            // Write the string to the file
                            bmOverlay.compress(Bitmap.CompressFormat.JPEG, 90, fout);
                            fout.flush();
                            fout.close();
                        }
                        catch (FileNotFoundException e)
                        {
                            // TODO Auto-generated catch block
                            Log.d("ImageCapture", "FileNotFoundException");
                            Log.d("ImageCapture", e.getMessage());
                            filePath = "";
                        }
                        catch (IOException e)
                        {
                            // TODO Auto-generated catch block
                            Log.d("ImageCapture", "IOException");
                            Log.d("ImageCapture", e.getMessage());
                            filePath = "";
                        }

                        openShareImageDialog(filePath);


                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };

           ;


            map.snapshot(callback);
        }
于 2015-07-16T03:29:12.930 回答
2
private GoogleMap mMap;
SupportMapFragment mapFragment;
LinearLayout linearLayout;
String jobId="1";

档案档案;

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

    linearLayout=(LinearLayout)findViewById (R.id.linearlayout);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
     mapFragment = (SupportMapFragment)getSupportFragmentManager ()
            .findFragmentById (R.id.map);
    mapFragment.getMapAsync (this);
    //Taking Snapshot of Google Map


}



/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng (-26.888033, 75.802754);
    mMap.addMarker (new MarkerOptions ().position (sydney).title ("Kailash Tower"));
    mMap.moveCamera (CameraUpdateFactory.newLatLng (sydney));
    mMap.setOnMapLoadedCallback (new GoogleMap.OnMapLoadedCallback () {
        @Override
        public void onMapLoaded() {
            snapShot();
        }
    });
}

// Initializing Snapshot Method
public void snapShot(){
    GoogleMap.SnapshotReadyCallback callback=new GoogleMap.SnapshotReadyCallback () {
        Bitmap bitmap;
        @Override
        public void onSnapshotReady(Bitmap snapshot) {
            bitmap=snapshot;
            bitmap=getBitmapFromView(linearLayout);
            try{
               file=new File (getExternalCacheDir (),"map.png");
                FileOutputStream fout=new FileOutputStream (file);
                bitmap.compress (Bitmap.CompressFormat.PNG,90,fout);
                Toast.makeText (MapsActivity.this, "Capture", Toast.LENGTH_SHORT).show ();
                sendSceenShot (file);
            }catch (Exception e){
                e.printStackTrace ();
                Toast.makeText (MapsActivity.this, "Not Capture", Toast.LENGTH_SHORT).show ();
            }


        }
    };mMap.snapshot (callback);
}
private Bitmap getBitmapFromView(View view) {
    Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas (returnedBitmap);
    Drawable bgDrawable =view.getBackground();
    if (bgDrawable!=null) {
        //has background drawable, then draw it on the canvas
        bgDrawable.draw(canvas);
    }   else{
        //does not have background drawable, then draw white background on the canvas
        canvas.drawColor(Color.WHITE);
    }
    view.draw(canvas);
    return returnedBitmap;
}

//Implementing Api using Retrofit
private void sendSceenShot(File file) {
    RequestBody job=null;

    Gson gson = new GsonBuilder ()
            .setLenient ()
            .create ();

    Retrofit retrofit = new Retrofit.Builder ()
            .baseUrl (BaseUrl.url)
            .addConverterFactory (GsonConverterFactory.create (gson))
            .build ();

    final RequestBody requestBody = RequestBody.create (MediaType.parse ("image/*"),file);
    job=RequestBody.create (MediaType.parse ("text"),jobId);


    MultipartBody.Part  fileToUpload = MultipartBody.Part.createFormData ("name",file.getName (), requestBody);

    API service = retrofit.create (API.class);
    Call<ScreenCapture_Pojo> call=service.sendScreen (job,fileToUpload);
    call.enqueue (new Callback<ScreenCapture_Pojo> () {
        @Override
        public void onResponse(Call <ScreenCapture_Pojo> call, Response<ScreenCapture_Pojo> response) {
            if (response.body ().getMessage ().equalsIgnoreCase ("Success")){
                Toast.makeText (MapsActivity.this, "success", Toast.LENGTH_SHORT).show ();
            }
        }

        @Override
        public void onFailure(Call <ScreenCapture_Pojo> call, Throwable t) {

        }
    });

}

}

于 2018-05-30T07:41:59.177 回答
1

我希望这将有助于捕获您的地图的屏幕截图

方法调用:

gmap.setOnMapLoadedCallback(mapLoadedCallback);

方法声明:

final SnapshotReadyCallback snapReadyCallback = new SnapshotReadyCallback() {
        Bitmap bitmap;
        @Override
        public void onSnapshotReady(Bitmap snapshot) {
            bitmap = snapshot;

            try {

                //do something with your snapshot

                imageview.setImageBitmap(bitmap);

            } catch (Exception e) {
                e.printStackTrace();
            }


        }
    };

GoogleMap.OnMapLoadedCallback mapLoadedCallback = new GoogleMap.OnMapLoadedCallback() {
        @Override
        public void onMapLoaded() {
            gmap.snapshot(snapReadyCallback);
        }
};
于 2018-02-22T18:09:59.313 回答
0

使用 mapcalback 获取地图截图

 GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback() {
                    Bitmap bitmap=null;
                    @Override
                    public void onSnapshotReady(Bitmap snapshot) {
                        // TODO Auto-generated method stub
                        bitmap = snapshot;
                        try {
                            saveImage(bitmap);
                            Toast.makeText(getActivity().getApplicationContext(), "Successful.Screenshot Saved.", Toast.LENGTH_LONG).show();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    private void saveImage(Bitmap bitmap) throws IOException {
                        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

                        Date date = new Date();
                        CharSequence format = android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", date);
                        String dirpath = Environment.getExternalStorageDirectory() + "";
                        File file = new File(dirpath);
                        if (!file.exists()) {
                            boolean mkdir = file.mkdir();
                        }
                        String path1 = dirpath + "/Documents/SCREENSHOT/";
                        File imageurl1 = new File(path1);
                        imageurl1.mkdirs();
                        File f = new File(path1 +"/"+ format + ".png");
                        f.createNewFile();
                        FileOutputStream fo = new FileOutputStream(f);
                        fo.write(bytes.toByteArray());
                        fo.close();
                    }
                };
                mMap.snapshot(callback);
于 2021-12-14T08:50:01.653 回答
-2

Eclipse DDMS 即使是谷歌地图 V2 也可以捕获屏幕。

如果您有“root”权限,请尝试调用 /system/bin/screencap 或 /system/bin/screenshot。我从Eclipse android DDMS 如何实现“屏幕捕获”中了解到

于 2013-02-06T09:01:22.490 回答