Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

If you have a pixel perfect line like 1:16 pixels, and you want to draw that same line rotated by a degree, for example 45°, what would be the correct way to do that by hand?

I know it should have something like n:n pixels, but 16:16 pixels just looks like it is to long to be the same line.

So what would the correct size would be for that pixel? And is there some kind of formula to calculate it with any degree?

share|improve this question
you are correct , the line is too long , it's 22.627416997969520780827019587355 units – Raxvan Nov 29 '13 at 15:22
Take into account the Pixel Aspect Ratio – Dan Nov 29 '13 at 15:46
Also there is the subpixel aliasing to be taken into account: – Raxvan Nov 29 '13 at 15:57
up vote 2 down vote accepted

If you want to draw a line "by hand" then you can use Bresenham's Algorithm. The algorythm take two 2d points and draws a line.

So given point A and a length L , here is how you compute point B to draw the line from A to B (depending on the axis: x from left to right, y from down to up)

point2d B;
B.x = cos(Angle) * L + A.x;
B.y = sin(Angle) * L + A.y;
share|improve this answer

This is just so you understand the logic behind drawing lines, if you understand Bresenham that might be the better option to implement.

A truly perfect pixel line is rather simple, you just need to calculate the ratio like you did in the question, the ratio is the angle of the line. A 45° degree line will have a ratio of 1:1.

Imagine moving a brush, if you have a 1:4 line that means for every 4 pixels you move on the y-axis you have to move one pixel on the x-axis.

enter image description here

Code for that could look like this:

int width = targetX - startX;
int height = targetY - startY;
// At least one of these will be 1
// Depending on wether width or height is larger.
int wRatio = (width / height) || 1 * (width / abs(width)); 
int hRatio = (height / width) || 1 * (height / abs(height));
int iterations = max(width / wRatio, height / hRatio);
int i = 0;
while(i++ < iterations)
  [... draw line segment (filled rectangle) at x,y with width wRatio and height hRatio ...]
  x += wRatio;
  y += hRatio;

However, sometimes you get don't get around ratios like 1:3.5632, in this case a truly pixel perfect line is not possible. A common approach is alternating between different length line segments and this will also be the case in Bresenham.

enter image description here

share|improve this answer

Your Answer


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.