将mapView另存为图像而不在屏幕上呈现

时间:2018-09-11 12:55:21

标签: android osmdroid

我正在创建类似于Strava的免费活动监控应用。使用vtm-android作为地图库。

我想将org.oscim.android.MapView另存为图像,而不呈现到屏幕上。

我找到了几种解决方案,如何将视图另存为图像,但是不幸的是,当视图未“附加”到现有组件树时,这些解决方案都无法正常工作。

我的期望是像这样初始化MapView:

final String MAP_FILE = "somemap.map";
MapView mapView = new MapView(mContext);

final org.oscim.map.Map map = mapView.map();
MapFileTileSource tileSource = new MapFileTileSource();

String mapPath = new File(Environment.getExternalStorageDirectory(), MAP_FILE).getAbsolutePath();
if (tileSource.setMapFile(mapPath)) {
    // Vector layer
    VectorTileLayer tileLayer = map.setBaseMap(tileSource);

    // Render theme
    map.setTheme(VtmThemes.DEFAULT);

    double latitude = 49.1625214;
    double longitude = 20.2644075;

    // Note: this map position is specific to Berlin area
    map.setMapPosition(latitude, longitude, 1 << 12);
}

mapView.layout(0, 0, 200, 200);

//Get the dimensions of the view so we can re-layout the view at its current size
//and create a bitmap of the same size
int width = view.getWidth();
int height = view.getHeight();

int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);

//Cause the view to re-layout
view.measure(measuredWidth, measuredHeight);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

//Create a bitmap backed Canvas to draw the view into
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);

//Now that the view is laid out and we have a canvas, ask the view to draw itself into the canvas
view.draw(canvas);

ByteBuffer byteBuffer = ByteBuffer.allocate(bitmap.getByteCount());
bitmap.copyPixelsToBuffer(byteBuffer);

//save bytes from bytebuffer to file or db

但是我得到的是完全透明的图像,而不是地图图像。

2 个答案:

答案 0 :(得分:0)

要拍摄屏幕快照,您需要在屏幕上进行渲染。没有渲染截图是不可能的

答案 1 :(得分:0)

mapView.getDrawingCache()

  

它将返回您当前显示的位图。

已捕获位图= Bitmap.createBitmap(mapView.getDrawingCache()); imageView.setImageBitmap(capturedScreen);

此处“ capturedScreen”将为您提供mapview的图像。