본문 바로가기

Android/MapView Screen Capture

안드로이드 구글맵 스크린 캡쳐 예제

안드로이드의 구글맵을 이용한 지도화면에서 화면을 캡쳐하여 파일에 저장하는 예제

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

map_layout.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:id="@+id/mainlayout"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent" >


    <com.google.android.maps.MapView

        android:id="@+id/mapview"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"

        android:clickable="true"

        android:apiKey="0lbzaFTEjuc25uPzbG67FsR1mDuQ7c2jSSj_Gzg"

    />

</RelativeLayout>



package test.android.hello;


import java.io.File;

import java.io.FileOutputStream;

import java.util.*;


import android.content.Context;

import android.graphics.*;

import android.graphics.Bitmap.CompressFormat;

import android.location.Criteria;

import android.location.Location;

import android.location.LocationListener;

import android.location.LocationManager;

import android.os.Bundle;

import android.os.Environment;

import android.util.Log;

import android.view.*;

import android.view.ContextMenu.ContextMenuInfo;

import android.view.View.MeasureSpec;

import android.widget.Toast;


import com.google.android.maps.*;


public class GoogleMapActivity extends MapActivity implements LocationListener {


    MapView mapView; 

    MapController mapController;

    GeoPoint p;


    LocationManager locationMgr;

    

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.map_layout);


        mapView = (MapView) findViewById(R.id.mapview);

        mapView.displayZoomControls(true);

        mapView.setBuiltInZoomControls(true);

        mapController = mapView.getController();


        locationMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        Criteria criteria = new Criteria();

        criteria.setAccuracy(Criteria.NO_REQUIREMENT);

        criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);

        String best = locationMgr.getBestProvider(criteria, true);

        locationMgr.requestLocationUpdates(best, 1000, 0, this);

        

        MapOverlay mapOverlay = new MapOverlay();

        List<Overlay> listOfOverlays = mapView.getOverlays();

        listOfOverlays.clear();

        listOfOverlays.add(mapOverlay);   

    }

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

menu.add(0,0,0,"지도 저장");

menu.add(0,1,0, "지도 첨부");

return true;

    }


    @Override

    public boolean onOptionsItemSelected(MenuItem item) {

switch(item.getItemId()){

case 0: Log.i("메뉴선택", "지도 저장 선택");

saveScreen();

break;

case 1: Log.i("메뉴선택", "지도 첨부 선택");

break;

}

return true;

    }


    private void saveScreen() {

View v = findViewById(R.id.mainlayout);

v.setDrawingCacheEnabled(true);


// this is the important code :)  

// Without it the view will have a dimension of 0,0 and the bitmap will be null          

v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 

           MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight()); 


v.buildDrawingCache(true);

Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());

v.setDrawingCacheEnabled(false); // clear drawing cache

v.destroyDrawingCache();

File file = new File( Environment.getExternalStorageDirectory() + "/capture.png");

try 

{

   file.createNewFile();

   FileOutputStream ostream = new FileOutputStream(file);

   bitmap.compress(CompressFormat.PNG, 100, ostream);

           ostream.close();

   Log.i("스크린캡쳐 결과", "스크린캡쳐, 파일저장 성공");

catch (Exception e) 

{

           e.printStackTrace();

}

    }


@Override

    protected boolean isRouteDisplayed() {

        return true;

    }


@Override

public void onLocationChanged(Location location) {

double lat = location.getLatitude();

double lon = location.getLongitude();

GeoPoint newPoint = new GeoPoint((int)(lat * 1E6), (int)(lon*1E6));

mapController.animateTo(newPoint);

p = newPoint;

}


@Override

public void onProviderDisabled(String provider) {}


@Override

public void onProviderEnabled(String provider) {}


@Override

public void onStatusChanged(String provider, int status, Bundle extras) {}

    

    class MapOverlay extends com.google.android.maps.Overlay  {

        @Override

        public boolean draw(Canvas canvas, MapView mapView, 

                                 boolean shadow, long when) {

            super.draw(canvas, mapView, shadow);                   


            //지리좌표를 화면픽셀좌표로 변환

            Point screenPts = new Point();

            if(p != null) mapView.getProjection().toPixels(p, screenPts);


            //위에서 변환한 화면좌표에 화살표 이미지를 그려준다

            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.arrow);

            Paint paint = new Paint();

            paint.setAlpha(50);

            canvas.drawBitmap(bmp, screenPts.x-bmp.getWidth()/2, screenPts.y, paint);         

            return true;

        }

        

        /*

         ACTION_MOVE나 멀티터치의 경우에는 화면에 화살표를 그리지 않고 손가락으로 터치 후 업 동작을 

         할 경우에만 해당 위치에 화살표를 그려주기 위해 좌표를 p 변수에 할당한다

        */

        boolean isTouched;

        @Override

        public boolean onTouchEvent(MotionEvent event, MapView mapView) {

        if(event.getAction()== MotionEvent.ACTION_DOWN) {

        isTouched = true;

        }else if(event.getAction()== MotionEvent.ACTION_MOVE) {

        isTouched = false;

        }

        if (event.getAction() == MotionEvent.ACTION_UP && isTouched) {

            // 터치된 화면의 좌표를 지리좌표로 변환한다 

                GeoPoint touchGP = mapView.getProjection().fromPixels(

                    (int)event.getX(),

                    (int)event.getY());

                //android.util.Log.e("터치 이벤트", "위도:"+touchGP.getLatitudeE6()+", 경도:"+touchGP.getLongitudeE6());

                p = touchGP;

                isTouched = false;

                return false;

            }

            return false;

        }

    }

}