Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 1 down vote accepted

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

share|improve this answer
    
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? –  Thomas Nov 27 '12 at 14:59
    
This may help you: stackoverflow.com/questions/8197656/… –  amb Nov 27 '12 at 18:18
    
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 –  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);
rotateMat.mapPoints(linePts);

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

Hope this helps.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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