Can a matrix be used when drawing lines and paths on android?

the DrawBitmap mathod takes a matrix as argument, I cannot find anything similar when drawing lines.


The Android Canvas drawBitmap method uses the matrix to transform the image as it is drawn. See this URL for the details: "http://developer.android.com/reference/android/graphics/Canvas.html#drawBitmap(android.graphics.Bitmap, android.graphics.Matrix, android.graphics.Paint)" [sorry, the link is breaking at the commas, cut-n-paste url]

There are several drawLine methods on the Canvas object, but none take a matrix as a parameter. See "http://developer.android.com/reference/android/graphics/Canvas.html#drawLine(float, float, float, float, android.graphics.Paint)" [sorry, the link is breaking at the commas, cut-n-paste url]

Your best bet is to use one of the Canvas's rotate, skew, and translate methods. See http://developer.android.com/reference/android/graphics/Canvas.html

| improve this answer | |
  • \$\begingroup\$ Does this allow me to rotate, skew and translate every separate bitmap too? I am currently able to draw and transform a full hierarchical tree of objects (containing a bitmap, position and rotation vectors). This means if I translate the parent (e.g. world object) every sub-object transforms with it accordingly. If i only transform the canvas, is this still possible then? \$\endgroup\$ – Thomas Nov 27 '12 at 14:59
  • \$\begingroup\$ This may help you: stackoverflow.com/questions/8197656/… \$\endgroup\$ – amb Nov 27 '12 at 18:18
  • \$\begingroup\$ What I have now is more complex then this example since it concatenates matrices from the parent objects, when I apply the matrix to the canvas instead of the bitmap it gets messed up, but I will continue trying \$\endgroup\$ – Thomas Nov 27 '12 at 19:17

I finally figured out how to use a matrix to do transformation on lines in Android.

It's a little roundabout but hope it helps someone.

The following code is to rotate a line around it's center.

//coordinates of line (x1,y1) to (x2,y2)
float x1,y1,x2,y2; 

//get the center of the line
float centerX = Math.abs((x1+x2)/2);
float centerY = Math.abs(y1+y2)/2;

//set the angle
double angle = 90;

//put the lines in an array
float linePts = new float[] {x1, y1, x2, y2};

//create the matrix
Matrix rotateMat = new Matrix();

//rotate the matrix around the center               
rotateMat.setRotate((float) angle, centerX, centerY);

//draw the line
mcanvas.drawLine(linePts [0], linePts [1], linePts [2], linePts [3], mPaint);

Hope this helps.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.