Wednesday, 9 January 2019

Android save polygon from map as bitmap same size for all devices

I am drawing polygon on Google map and it works great. What I need is to save this polygon as bitmap for fixed scale. I am using this code to do that.

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;
}

And then to create bitmap

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;
        }

The problem is that this method uses screen projection and when user changes zoom or drags map it changes polygon position on bitmap or its even out of bounds. How can I make it to draw the same size polygon on all devices not depending on zoom, or camera position?



from Android save polygon from map as bitmap same size for all devices

No comments:

Post a Comment