Capture d’écran de Google API Google API V2

Mise à jour finale

La demande de fonctionnalité a été remplie par Google. S’il vous plaît voir cette réponse ci-dessous.

Question originale

Grâce à l’ancienne version de l’API Google Maps Android, j’ai pu capturer une capture d’écran de la carte Google pour la partager via les médias sociaux. J’ai utilisé le code suivant pour capturer la capture d’écran et enregistrer l’image dans un fichier et cela a fonctionné très bien:

public Ssortingng captureScreen() { Ssortingng storageState = Environment.getExternalStorageState(); Log.d("StorageState", "Storage state is: " + storageState); // image naming and path to include sd card appending name you choose for file Ssortingng 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; Ssortingng filePath = System.currentTimeMillis() + ".jpeg"; try { fout = openFileOutput(filePath, MODE_WORLD_READABLE); // Write the ssortingng 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; } 

Cependant, le nouvel object GoogleMap utilisé par V2 de l’API ne possède pas de méthode “getRootView ()” comme le fait MapView.

J’ai essayé de faire ça:

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

Mais la capture d’écran que je reçois n’a pas de contenu de carte et ressemble à ceci: Capture d'écran de la carte vierge

Quelqu’un at-il compris comment faire une capture d’écran de la nouvelle API Google Maps Android V2?

Mettre à jour

J’ai également essayé d’obtenir le rootView de cette façon:

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

Cela se traduit par une capture d’écran qui inclut la barre d’action en haut de l’écran, mais la carte est toujours vide comme la capture d’écran que j’ai jointe.

Mettre à jour

Une demande de fonctionnalité a été soumise à Google. S’il vous plaît aller à la demande de fonctionnalité si c’est quelque chose que vous souhaitez append à Google à l’avenir: Ajouter une capacité de capture d’écran à Google Maps API V2

Mise à jour – Google a ajouté une méthode de capture instantanée ** !:

La demande de fonctionnalité pour une méthode de capture d’écran de la couche OpenGL Android Google Map API V2 a été satisfaite.

Pour prendre une capture d’écran, implémentez simplement l’interface suivante:

 public abstract void onSnapshotReady (Bitmap snapshot) 

et appelez:

public final void snapshot (GoogleMap.SnapshotReadyCallback callback)

Exemple qui prend une capture d’écran, puis présente les options standard de “partage d’images”:

 public void captureScreen() { SnapshotReadyCallback callback = new SnapshotReadyCallback() { @Override public void onSnapshotReady(Bitmap snapshot) { // TODO Auto-generated method stub bitmap = snapshot; OutputStream fout = null; Ssortingng filePath = System.currentTimeMillis() + ".jpeg"; try { fout = openFileOutput(filePath, MODE_WORLD_READABLE); // Write the ssortingng 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); } 

Une fois l’image capturée, elle déclenche la boîte de dialog standard “Partager l’image” afin que l’utilisateur puisse choisir comment le partager:

 public void openShareImageDialog(Ssortingng 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.ssortingng.shareImageFailed); } } 

La documentation est ici

Voici les étapes à suivre pour capturer une capture d’écran de Google Map V2 avec un exemple

Étape 1. Ouvrez Android Sdk Manager (Window > Android Sdk Manager) puis Expand Extras maintenant update/install Google Play Services to Revision 10 ignorez cette étape si elle est déjà installed

Lisez les notes ici https://developers.google.com/maps/documentation/android/releases#august_2013

Étape 2. Restart Eclipse

Etape 3. import com.google.android.gms.maps.GoogleMap.SnapshotReadyCallback;

Étape 4. Méthode pour capturer / stocker l’écran / image de la carte, comme ci-dessous

 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(); } 

Étape 5. Appelez maintenant cette méthode CaptureMapScreen() où vous voulez capturer l’image

dans mon cas, calling this method on Button click in my onCreate() qui fonctionne bien

comme:

 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(); } } }); 

Vérifiez Doc ici et ici

Edit : cette réponse n’est plus valide – la demande de fonctionnalités pour les captures d’écran sur Google Maps Android API V2 a été remplie. Voir cette réponse pour un exemple .

Original accepté réponse

Comme les nouvelles cartes Android API v2 sont affichées avec OpenGL, il n’est pas possible de créer une capture d’écran.

Étant donné que la réponse la plus votée ne fonctionne pas avec les polylignes et autres superpositions au-dessus du fragment de carte (ce que je cherchais), je souhaite partager cette solution.

 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 Masortingx(), null); canvas.drawBitmap(backBitmap, 0, 0, null); OutputStream fout = null; Ssortingng filePath = System.currentTimeMillis() + ".jpeg"; try { fout = openFileOutput(filePath, MODE_WORLD_READABLE); // Write the ssortingng 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); } 
 private GoogleMap mMap; SupportMapFragment mapFragment; LinearLayout linearLayout; Ssortingng jobId="1"; 

Fichier de fichier;

 @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 sortingggered 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 sortingggered 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 call=service.sendScreen (job,fileToUpload); call.enqueue (new Callback () { @Override public void onResponse(Call  call, Response response) { if (response.body ().getMessage ().equalsIgnoreCase ("Success")){ Toast.makeText (MapsActivity.this, "success", Toast.LENGTH_SHORT).show (); } } @Override public void onFailure(Call  call, Throwable t) { } }); } 

}

J’espère que cela aidera à capturer la capture d’écran de votre carte

Appel de méthode:

 gmap.setOnMapLoadedCallback(mapLoadedCallback); 

Déclaration de méthode:

 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); } }; 

J’ai capturé capture d’écran de carte.Il sera utile

  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(); } }); } 

`

Méthode snapShot () pour prendre une capture d’écran de la carte

  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); } 

Ma sortie est ci-dessous entrer la description de l'image ici

Eclipse DDMS peut capturer l’écran même s’il s’agit de Google map V2.

Essayez d’appeler / system / bin / screencap ou / system / bin / screenshot si vous avez la racine. J’ai appris cela de comment Eclipse android DDMS implémenter “capture d’écran”