有时候我们会遇到要截取地图的情况,下面就百度地图的截图来简单的写一下。
下面直接上代码(注册百度地图开发者账号,创建一个应用,获得Appkey):
用到的jar包及目录结构:
libs文件下载地址:http://pan.baidu.com/s/1bompnif 提取码:bwlq
代码:
a:AndroidManifest.xml
清单文件中添加所需权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
<permission android:name="android.permission.BAIDU_LOCATION_SERVICE"></permission>
<uses-permission android:name="android.permission.BAIDU_LOCATION_SERVICE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCES_MOCK_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_GPS" />
添加服务:
<service android:name="com.baidu.location.f"
android:enabled="true"
android:process=":remote">
</service>
b:创建BaiduApp.java,继承Application,实现对地图的管理:
public class BaiduApp extends Application {
private static MyBaiduApp mInstance = null;
public boolean m_bKeyRight = true;
BMapManager mBMapManager = null;
public static final String strKey = "2621E561945597BBE213F4208E2CAAB74DA1B57F";//AppKey
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
mInstance = this;
initEngineManager(this);
public void initEngineManager(Context context) {
if (mBMapManager == null) {
mBMapManager = new BMapManager(context);
}
if (!mBMapManager.init(strKey, new MyGeneralListener())) {
Toast.makeText(MyBaiduApp.getInstance().getApplicationContext(), "BMapManager 初始化错误!", Toast.LENGTH_LONG)
.show();
}
}
@Override
// 建议在您app的退出之前调用mapadpi的destroy()函数,避免重复初始化带来的时间消耗
public void onTerminate() {
if (mBMapManager != null) {
mBMapManager.destroy();
mBMapManager = null;
}
super.onTerminate();
}
public static MyBaiduApp getInstance() {
return mInstance;
}
// 常用事件监听,用来处理通常的网络错误,授权验证错误等
static class MyGeneralListener implements MKGeneralListener {
@Override
public void onGetNetworkState(int iError) {
if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
Toast.makeText(MyBaiduApp.getInstance().getApplicationContext(), "您的网络出错啦!", Toast.LENGTH_LONG).show();
} else if (iError == MKEvent.ERROR_NETWORK_DATA) {
Toast.makeText(MyBaiduApp.getInstance().getApplicationContext(), "输入正确的检索条件!", Toast.LENGTH_LONG)
.show();
}
}
@Override
public void onGetPermissionState(int iError) {
if (iError == MKEvent.ERROR_PERMISSION_DENIED) {
// 授权Key错误:
Toast.makeText(MyBaiduApp.getInstance().getApplicationContext(), "请在 DemoApplication.java文件输入正确的授权Key!",
Toast.LENGTH_LONG).show();
MyBaiduApp.getInstance().m_bKeyRight = false;
}
}
}
}
c:DensityUtil.java优化截图效果
/*
* 屏幕分辨率获取的类
*/
public class DensityUtil {
private static int[] deviceWidthHeight = new int[2];
public static int[] getDeviceInfo(Context context) {
if ((deviceWidthHeight[0] == 0) && (deviceWidthHeight[1] == 0)) {
DisplayMetrics metrics = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(metrics);
deviceWidthHeight[0] = metrics.widthPixels;
deviceWidthHeight[1] = metrics.heightPixels;
}
return deviceWidthHeight;
}
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
}
d:Config.java类,
public class Config {
public static int[] deviceWidthHeight ;
}
e:BitmapUtils.java,截图的加载
public class BitmapUtils {
public static Bitmap drawableToBitamp(Drawable drawable) {
Bitmap bitmap = null;
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();
Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565;
bitmap = Bitmap.createBitmap(w, h, config);
// 注意,下面三行代码要用到,否在在View或者surfaceview里的canvas.drawBitmap会看不到图
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
drawable.draw(canvas);
return bitmap;
}
public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
}
f:BaiduActivity.java
public class BaiduActivity extends Activity {
private MapView mMapView = null;
MyBaiduApp app;
private ImageView pos_IV;
private MapController mMapController = null;
MKMapViewListener mMapListener = null;
// 定位相关
LocationClient mLocClient;
public MyLocationListenner myListener = new MyLocationListenner();
MKSearch mMKSearch;
LocationData locData = null;
GeoPoint geoPoint;// 当前位置
MyLocationOverlay myLocationOverlay = null;
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
// 定位当前位置调用reverseGeocode方法获取实现接口类里的当前位置Toast信息
mMKSearch.reverseGeocode(geoPoint);
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_baidu);
findViews();
setApp();
initMapView();
getListener();
setListener();
getMapClient();
}
/*
* 获取监听
*/
private void getListener() {
mMapListener = new MKMapViewListener() {
@Override
public void onMapMoveFinish() {
// T在此处理地图移动完成消息回调
}
@Override
public void onClickMapPoi(MapPoi mapPoiInfo) {
// TODO Auto-generated method stub
String title = "";
if (mapPoiInfo != null) {
title = mapPoiInfo.strText;
Toast.makeText(BaiduActivity.this, title, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onGetCurrentMap(Bitmap bitmap) {
// 回调图片数据,保存在"/mnt/sdcard/test"目录下
System.out.println("test" + "onGetCurrentMap");
File file = new File("/mnt/sdcard/baidupos.png");
FileOutputStream out;
try {
out = new FileOutputStream(file);
// 获取状态栏高度
Rect frame = new Rect();
BaiduActivity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
bitmap = Bitmap.createBitmap(bitmap,
Integer.parseInt("" + (Config.deviceWidthHeight[0] / 2 - Config.deviceWidthHeight[0] / 6)),
Integer.parseInt("" + (Config.deviceWidthHeight[1] / 2 - Config.deviceWidthHeight[0] / 6
- statusBarHeight / 2)),
Config.deviceWidthHeight[0] / 3, Config.deviceWidthHeight[0] / 3);
pos_IV.setImageBitmap(BitmapUtils.toRoundCorner(bitmap, 15));
if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
out.flush();
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onMapAnimationFinish() {
// TODO Auto-generated method stub
}
};
}
public class MyMKSearchListener implements MKSearchListener {
@Override
public void onGetAddrResult(MKAddrInfo res, int error) {
// 获取地理位置信息
if (error != 0) {
String str = String.format("错误号:%d", error);
return;
}
String posInfo = String.format("纬度:%f 经度:%f 地址:%s\r\n", res.geoPt.getLatitudeE6() / 1e6,
res.geoPt.getLongitudeE6() / 1e6,
res.addressComponents.city + res.addressComponents.district + res.addressComponents.street);
Toast.makeText(BaiduActivity.this, posInfo, 1).show();
}
@Override
public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onGetDrivingRouteResult(MKDrivingRouteResult arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onGetPoiDetailSearchResult(int arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onGetTransitRouteResult(MKTransitRouteResult arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onGetWalkingRouteResult(MKWalkingRouteResult arg0, int arg1) {
// TODO Auto-generated method stub
}
}
private void getMapClient() {
myLocationOverlay = new MyLocationOverlay(mMapView);
locData = new LocationData();
myLocationOverlay.setData(locData);
mMapView.getOverlays().add(myLocationOverlay);
myLocationOverlay.enableCompass();
mMapView.refresh();
}
/*
* 设置监听
*/
private void setListener() {
mMapView.regMapViewListener(MyBaiduApp.getInstance().mBMapManager, mMapListener);
}
/**
* 监听函数,又新位置的时候,格式化成字符串,输出到屏幕中
*/
public class MyLocationListenner implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
if (location == null) {
return;
}
locData.latitude = location.getLatitude();
locData.longitude = location.getLongitude();
locData.accuracy = location.getRadius();
locData.direction = location.getDerect();
myLocationOverlay.setData(locData);
mMapView.refresh();
geoPoint = new GeoPoint((int) (locData.latitude * 1e6), (int) (locData.longitude * 1e6));
mMapController.animateTo(geoPoint, mHandler.obtainMessage(1));
}
public void onReceivePoi(BDLocation poiLocation) {
if (poiLocation == null) {
return;
}
}
}
/*
* 获取控件
*/
private void findViews() {
mMapView = (MapView) findViewById(R.id.bmapView);
pos_IV = (ImageView) findViewById(R.id.pos_IV);
Config.deviceWidthHeight = DensityUtil.getDeviceInfo(this);
System.out.println("widthpx=" + Config.deviceWidthHeight[0] + "**heightpx=" + Config.deviceWidthHeight[1]);
}
/*
* 设置APP
*/
private void setApp() {
app = (MyBaiduApp) this.getApplication();
if (app.mBMapManager == null) {
app.mBMapManager = new BMapManager(this);
app.mBMapManager.init(MyBaiduApp.strKey, new MyBaiduApp.MyGeneralListener());
}
}
/*
* 初始化地图 数据
*/
private void initMapView() {
mMapController = mMapView.getController();
mLocClient = new LocationClient(this);
mLocClient.registerLocationListener(myListener);
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true);// 打开gps
option.setAddrType("all");// 返回的定位结果包含地址信息
option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02 可以无偏差的显示在百度地图上
option.setScanSpan(5000);// 设置发起定位请求的间隔时间为5000ms
option.disableCache(true);// 禁止启用缓存定位
option.setPoiNumber(5); // 最多返回POI个数
option.setPoiDistance(1000); // poi查询距离
option.setPriority(LocationClientOption.GpsFirst);// gps优先
option.setPoiExtraInfo(true); // 是否需要POI的电话和地址等详细信息
mLocClient.setLocOption(option);
mLocClient.start();
mMapView.getController().setZoom(15);
mMapView.getController().enableClick(true);
mMapView.setBuiltInZoomControls(true);
GeoPoint centerpt = mMapView.getMapCenter();
int maxLevel = mMapView.getMaxZoomLevel();
int zoomlevel = mMapView.getZoomLevel();
boolean isTraffic = mMapView.isTraffic();
boolean isSatillite = mMapView.isSatellite();
boolean isDoubleClick = mMapView.isDoubleClickZooming();
mMapView.setLongClickable(true);
// 初始化
mMKSearch = new MKSearch();
mMKSearch.init(app.mBMapManager, new MyMKSearchListener());
}
/*
* 按钮点击事件 获取截图,异步方法
*/
public void capturemapclick(View view) {
mMapView.getCurrentMap();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_baidu, menu);
return true;
}
@Override
protected void onPause() {
mMapView.onPause();
super.onPause();
}
@Override
protected void onResume() {
mMapView.onResume();
super.onResume();
}
@Override
protected void onDestroy() {
mMapView.destroy();
MyBaiduApp app = (MyBaiduApp) this.getApplication();
if (app.mBMapManager != null) {
app.mBMapManager.destroy();
app.mBMapManager = null;
}
super.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mMapView.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mMapView.onRestoreInstanceState(savedInstanceState);
}
public class NotifyLister extends BDNotifyListener {
public void onNotify(BDLocation mlocation, float distance) {
}
}
}
最后记得在清单文件中这儿修改一下哦