Скриншот приложения? - PullRequest
0 голосов
/ 27 июня 2018

У меня есть приложение Google Map Android, которое я пытаюсь сделать снимок экрана всего изображения вместе с картой. Снимок экрана сделан, но карта Google полностью черная только с логотипом Google. Я использую следующий код:

private void captureScreen() {
    View v = getWindow().getDecorView().getRootView();
    v.setDrawingCacheEnabled(true);
    Bitmap bmp = Bitmap.createBitmap(v.getDrawingCache());
    v.setDrawingCacheEnabled(false);
    try {
        FileOutputStream fos = new FileOutputStream(new File(Environment
                .getExternalStorageDirectory().toString(), "SCREEN"
                + System.currentTimeMillis() + ".png"));
        bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/mapLayout">

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
tools:context="net.aratos.adc.MapActivity"
android:layout_height="0dp"
android:layout_weight="0.8"/>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_weight="0.1"
    android:layout_gravity="center_horizontal">

    <Button
        android:gravity="center"
        android:id="@+id/loadDateButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Load date" />

    <Button
        android:gravity="center"
        android:id="@+id/snapshotButton"
        android:text="Snapshot"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:gravity="center"
        android:id="@+id/exportButton"
        android:text="Export PDF"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

<GridView
    android:orientation="horizontal"
    android:id="@+id/boundsLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:numColumns="auto_fit">

</GridView>
</LinearLayout>

Я также прилагаю код макета. Выходной скриншот выглядит следующим образом изображение

После попытки кода Бриеша я получаю следующий вывод

Ответы [ 3 ]

0 голосов
/ 27 июня 2018

Следующий код поможет вам

        googleMap.snapshot(new GoogleMap.SnapshotReadyCallback() {

        @Override
        public void onSnapshotReady(Bitmap bitmap) {
            try {
                FileOutputStream fos = new FileOutputStream(new File(Environment
                        .getExternalStorageDirectory().toString(), "SCREEN"
                        + System.currentTimeMillis() + ".png"));
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

чтобы захватить весь экран попробуйте следующий

        googleMap.snapshot(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);
                try {
                    FileOutputStream fos = new FileOutputStream(new File(Environment
                            .getExternalStorageDirectory().toString(), "SCREEN"
                            + System.currentTimeMillis() + ".png"));


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


            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
0 голосов
/ 28 июня 2018
public void captureMapScreen() {
    SnapshotReadyCallback callback = new SnapshotReadyCallback() {

        @Override
        public void onSnapshotReady(Bitmap snapshot) {
            try {
                mView.setDrawingCacheEnabled(true);
                Bitmap backBitmap = mView.getDrawingCache();
                Bitmap bmOverlay = Bitmap.createBitmap(
                        backBitmap.getWidth(), backBitmap.getHeight(),
                        backBitmap.getConfig());
                Canvas canvas = new Canvas(bmOverlay);
                canvas.drawBitmap(backBitmap, 0, 0, null);
                canvas.drawBitmap(snapshot, new Matrix(), null);
                FileOutputStream out = new FileOutputStream(
                        Environment.getExternalStorageDirectory()
                                + "/MapScreenShot"
                                + System.currentTimeMillis() + ".png");

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

    mMap.snapshot(callback);

}

Убедитесь, что вы используете android.graphics.Matrix , а не android.opengl.Matrix

Надеюсь, это поможет.

0 голосов
/ 27 июня 2018

Вы можете использовать метод GoogleMap.snapshot для создания снимков карты ( документация )

Вам нужно будет реализовать

GoogleMap.SnapshotReadyCallback

для управления сделанным снимком.

Также учтите, что согласно документации:

Примечание: Изображения карты не должны передаваться на ваши серверы, или в противном случае используется за пределами приложения. Если вам нужно отправить карту другому приложению или пользователю, отправьте данные, которые позволяют им реконструируйте карту для нового пользователя вместо снимка.

...