我在谷歌地图上绘制多边形,效果很好。我需要的是将这个多边形保存为固定比例的位图。我正在使用这段代码来做到这一点。
private static List<Point> scalePolygonPoints(List<LatLng> points, float scale, Projection projection) {
List<Point> scaledPoints = new ArrayList(points.size());
LatLng polygonCenter = getPolygonCenterPoint(points);
Point centerPoint = projection.toScreenLocation(polygonCenter);
for (int i=0; i < points.size(); i++) {
Point screenPosition = projection.toScreenLocation(points.get(i));
screenPosition.x = (int) (scale * (screenPosition.x - centerPoint.x) + centerPoint.x);
screenPosition.y = (int) (scale * (screenPosition.y - centerPoint.y) + centerPoint.y);
scaledPoints.add(screenPosition);
}
return scaledPoints;
}
private static LatLng getPolygonCenterPoint(List<LatLng> polygonPointsList){
LatLng centerLatLng = null;
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for(int i = 0; i < polygonPointsList.size() ; i++) {
builder.include(polygonPointsList.get(i));
}
LatLngBounds bounds = builder.build();
centerLatLng = bounds.getCenter();
return centerLatLng;
}
然后创建位图
private Bitmap createPolylineBitmap(List<Point> scaledPoints) {
Bitmap bitmap = Bitmap.createBitmap(800, 600, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setColor(ContextCompat.getColor(this, R.color.black));
paint.setStrokeWidth(10);
paint.setDither(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setAntiAlias(true);
for (int i = 0; i < scaledPoints.size(); i++) {
try {
canvas.drawLine(scaledPoints.get(i).x, scaledPoints.get(i).y, scaledPoints.get(i + 1).x, scaledPoints.get(i + 1).y, paint);
}
catch(Exception ex){
canvas.drawLine(scaledPoints.get(i).x, scaledPoints.get(i).y, scaledPoints.get(0).x, scaledPoints.get(0).y, paint);
}
}
return bitmap;
}
问题在于此方法使用屏幕投影,当用户更改缩放或拖动 map 时,它会更改位图上的多边形位置或其甚至越界。我怎样才能让它在所有设备上绘制相同大小的多边形而不取决于缩放或相机位置?
编辑: 所以基本上我设法在将其保存到位图之前在正确的位置获得正确大小的多边形缩放图。但问题是当我使用具有不同分辨率的设备时,多边形大小也在变化。如何预防?
最佳答案
一个可能对您有用的聪明技巧 - 为什么不在用户尝试保存地理围栏时手动缩放相机以适合折线。
val latLngs = getLatLngs()
val builder = LatLngBounds.Builder()
latLngs.forEach {
builder.include(it.position)
}
val padding = 200
val bounds = builder.build()
val cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, padding)
map.moveCamera(cameraUpdate)
//Do your projection operation here...
关于Android 将 map 中的多边形保存为所有设备大小相同的位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54065575/