Here's the function I ended up writing in case anyone wants something similar. I originally wrote a couple quick functions to do horizontal and vertical lines (which are all that I need). This function will work with diagonal lines as well. I make no claims about its efficiency.
The xStart, yStart and xEnd, yEnd arguments should be self-explanatory.
The linePattern argument determines the type of dashing or dotting that should be used. The function uses the binary pattern of the argument to do this. The least significant bit is used first.
Note that the pattern will not necessarily start a xStart, yStart. The end points may be changed around by the implentation of the Bresenham algorithm.
Some examples:
linePattern = 0x5555 will be a dotted line, alternating one drawn and one skipped pixel.
linePattern = 0x0F0F will be medium sized dashes.
linePattern = 0xFF00 will be large dashes.
The lineScale argument controls the size of the pattern. If you create a dotted line with linePattern = 0x5555 and a lineScale of 1, you will get a dotted line. If you use a lineScale of 2, you will get a dashed line with two pixels on, two off (the same as linePattern = 0x3333, lineScale = 1). lineScale is primarily there to allow much larger dashes and patterns that can't be defined with the 16 bits in linePattern. A lineScale of 0 is the same as 1.
The color is based on the current stroke() color.
Code:
//based on Bresenham's algorithm from wikipedia
//http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
void patternLine(int xStart, int yStart, int xEnd, int yEnd, int linePattern, int lineScale) {
int temp, yStep, x, y;
int pattern = linePattern;
int carry;
int count = lineScale;
boolean steep = (abs(yEnd - yStart) > abs(xEnd - xStart));
if (steep == true) {
temp = xStart;
xStart = yStart;
yStart = temp;
temp = xEnd;
xEnd = yEnd;
yEnd = temp;
}
if (xStart > xEnd) {
temp = xStart;
xStart = xEnd;
xEnd = temp;
temp = yStart;
yStart = yEnd;
yEnd = temp;
}
int deltaX = xEnd - xStart;
int deltaY = abs(yEnd - yStart);
int error = - (deltaX + 1) / 2;
y = yStart;
if (yStart < yEnd) {
yStep = 1;
} else {
yStep = -1;
}
for (x = xStart; x <= xEnd; x++) {
if ((pattern & 1) == 1) {
if (steep == true) {
point(y, x);
} else {
point(x, y);
}
carry = 0x8000;
} else {
carry = 0;
}
count--;
if (count <= 0) {
pattern = (pattern >> 1) + carry;
count = lineScale;
}
error += deltaY;
if (error >= 0) {
y += yStep;
error -= deltaX;
}
}
}
I'm not sure why some of the indenting above is a little funny.
Here's a very quick piece of code that draws dashed lines:
Code:
void setup() {
size (500,500);
stroke(0);
for (int i = 0; i <= 20; i++) {
int x = 10 + i * 10;
patternLine(x, 10, x, 400, 0x5555, i);
}
}
void draw() {
}