我有一个用于在我的MapView
. 因为在draw
我绘制路径的每一段的方法中,这很容易成为一个效率问题。
出于这个原因,我决定缓存叠加层的内容,并在必要时重新绘制它,即路径发生变化、地图中心移动或缩放级别发生变化时。
draw
现在,该方法的参数之一是Canvas
绘图。我知道如何在上面绘制缓存的位图,问题是我不知道如何在位图上缓存画布的内容。
我不能实例化一个新的画布,也不能调用setBitmap
,因为画布在 a 中,如果调用该方法HardwareCanvas
,它会抛出一个。UnsupportedOperationException
所以,回顾一下,我有一个画布和一个位图,我如何将画布的内容复制到位图?
为清楚起见,编辑
这是我的绘制方法,我不手动调用它,但即使地图根本没有移动,它仍然会被重复调用
public void draw(Canvas canvas, MapView map, boolean shadow) {
if (shadow) {
// this overlay doesn't need to draw shadows
return;
}
if (paths.isEmpty()) {
// nothing to draw
return;
}
center = map.getMapCenter();
zoomLevel = map.getZoomLevel();
map.getDrawingRect(bounds);
projection = map.getProjection();
maxLevel = map.getMaxZoomLevel();
for (MapPath mp : paths) {
// adjust path width to current zoom
adjustedWidth = mp.getWidth() * zoomLevel / maxLevel;
if (adjustedWidth < MIN_WIDTH_TO_DRAW) {
// path is too thin, avoid drawing it
continue;
}
paint.setStrokeWidth(adjustedWidth);
paint.setColor(mp.getColor());
state = PathState.FIRST_POINT;
path.reset();
for (PathPoint pp : mp.getPoints()) {
if (!pp.shoudAppearAtZoomLevel(zoomLevel)) {
// do not draw this point at this zoom level
continue;
}
// project a geopoint to a pixel
projection.toPixels(pp.getGeoPoint(), point);
inside = isInsideBounds(point, map);
switch (state) {
case FIRST_POINT:
// move to starting point
firstX = point.x;
firstY = point.y;
path.moveTo(firstX, firstY);
break;
case WAS_INSIDE:
// segment is completely or partially on map
path.lineTo(point.x, point.y);
break;
case WAS_OUTSIDE:
if (inside) {
// segment is partially on map
path.lineTo(point.x, point.y);
} else {
// segment is completely off map
path.moveTo(point.x, point.y);
}
break;
}
// update state
state = inside ? PathState.WAS_INSIDE : PathState.WAS_OUTSIDE;
}
// workaround to avoid canvas becoming too big when path is mostly off screen
path.moveTo(firstX, firstY);
// draw this path to canvas
canvas.drawPath(path, paint);
}
super.draw(canvas, map, shadow);
}