views:

997

answers:

1

Hi,

I am writing an Android app where one of the features is that the map will rotate according to the compass (i.e. if the phone is pointing east, the map will be oriented so that the east side of the map is on top). Previous answers that I have found suggested over writing the onDraw() method in mapView, however, the api changed the method to final so it cannot be overwritten. As a result I have tried to overwrite the dispatchDraw() method like so:

Note:

-compass is a boolean that if true, rotate the view

-bearing is a float variable that has the degrees that the view should rotate

protected void dispatchDraw(Canvas canvas) {
 canvas.save();
         if (compass) {
             final float w = this.getWidth();
             final float h = this.getHeight();

             final float scaleFactor = (float)(Math.sqrt(h * h + w * w) / Math.min(w, h));

             final float centerX = w / 2.0f;
             final float centerY = h / 2.0f;

             canvas.rotate(bearing, centerX, centerY);
             canvas.scale(scaleFactor, scaleFactor, centerX, centerY);

         }
         super.dispatchDraw(canvas);
         canvas.restore();
}
A: 

It should be something like this:

@Override
protected void dispatchDraw(Canvas canvas) {
    canvas.save(Canvas.MATRIX_SAVE_FLAG);
    if (compass) {
        // rotate the canvas with the pivot on the center of the screen
        canvas.rotate(-azimuth, getWidth() * 0.5f, getHeight() * 0.5f);
        super.dispatchDraw(canvas);
        canvas.restore();
    }
}
Cristian
Did it work for you? It did't work for me.
Michalis Giannakidis