I am trying to draw lines on android canvas by calculating the last point (X,Y) given a point (Xo,Yo), the distance and the angle. A diagram is illustrated below:
I am calculating the azimuth orientation angle degree using the below formula from magnetic sensor and accelerometer values
if (accelValues != null && magnetValues != null) { float rotation[] = new float[9]; float orientation[] = new float[3]; if (SensorManager.getRotationMatrix(rotation, null, accelValues, magnetValues)) { SensorManager.getOrientation(rotation, orientation); float azimuthDegree = (float) (Math.toDegrees(orientation[0]) + 360) % 360; orientationDegree = Math.round(azimuthDegree); } }
I am saving all lines in an array and afterwhich I am calling onDraw to repaint the canvas. Below are my codes for the onDraw and calculating the steps so it redraw the lines at each step the user is taking depending on his orientation. (Assuming the distance length is 60)
protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); drawRotateImage(canvas); canvas.drawPoint(Position.x_axis, Position.y_axis, paint); for (Line l : listLine) { canvas.drawLine(l.StartX, l.StartY, l.EndX, l.EndY, paint); }
private void stepDetector () { l = new Line(); l.setStartX(lastX); l.setStartY(lastY); l.setOrientationDegree(orientationDegree); lineX = (float) (lastX + (60 * cos(orientationDegree))); lineY = (float) (lastY + (60 * sin(orientationDegree))); l.setEndX(lineX); l.setEndY(lineY); listLine.add(l); System.out.println ("" + l.toString()); invalidate(); lastX = lineX; lastY = lineY; }
Problem I am facing is that the lines are not being drawn with the correct orientation. It is going in any direction irrespective of the orientation direction. I get something as shown below:
To what I have analyzed, the line are not being drawn accurately, given the orientationdegree. I believe it is something, relating to the Android Coordinate System. It would be grateful if someone can help me on this to calculate the exact orientation degree in any direction [0-360].
Is there a different equation for calculating the last point (X,Y) in each quadrant of the circle axis ?
Advertisement
Answer
I believe that the behaviour you are observing is due to the fact that your azimuth is in degrees whereas the trig functions expect radians. You could convert from degrees back to radians using Math.toRadians
. However, I would stick to using radians everywhere and do away with calling Math.toDegrees
(and stop rounding too).