I like to have maximum control over the screen, so I have to control every pixel, and that has some pros and cons. one con is that I don't really have the help from any built-in functions. so I have no idea how to draw a line. I've tried to make a function to handle line drawing but I just can't get it to work! here's the code I used to draw the line
int startX;
int startY;
int deltaX = x1/x2;
int deltaY = y1/y2;
float deltaPixl = deltaX/deltaY;
for(int i=0;i<deltaY;i=i+1){
if(x1>x2){ startX = x2;}else{ startX=x1;}
if(y1>y2){ startY = y2;}else{ startY=y1;}
pixl(startX+i,round(startY+(deltaPixl*i)),0);
}
it uses a function called pixl so that it easily draw a pixel to the pixel array, just to clarify why there's a function called pixl in the code.
and when I try to use this code, it doesn't crash, like processing usually does when it has an error! it just doesn't work, instead just doing nothing!
I'd like some help on this subject, please.
You could get away with simply using PGraphics. The idea is once you have a PGraphics instance you use dot notation to access the drawing functions used to (as long as they're called between
.beginDraw()
and.endDraw()
).Using
noSmooth()
you can get it looking pixel perfect.Here's a basic sketch to illustrate the idea:
This should do for most cases. (It's only trickier cases with very small values and transparency that might give you headaches)
If for some reason you need a lot more control, you can you always implement your own method of rasterising. Once place you can probably start with is Bresenham's line algorithm
Regarding your code there are a few things that could go wrong:
float deltaPixl = deltaX/deltaY;
: if deltaY is zero you'll run into an exceptiondeltaX
anddeltaY
(potentially making it likely to get 0 for either of the values)println()
statement before the for loop with the start/end values to get a feel if that loop will actually execute or not. Additionally, within thefor
loop you canprintln(i)
to see if you get the value you expect.Overall I recommend checking Kevin Workman's How to Debug guide.
Additionally you could use lerp() to calculate linearly interpolated position between the line's start and end points. Pass each coordinate and a normalized (between 0.0, 1.0) value, where 0.0 = at the start point, 1.0 = at the end point and anything in between is on the line (e.g. 0.5 = 50% along the line).
Here's a basic example:
For the sake of completeness here's the above snippet using the
pixels[]
instead: