#### Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

# Drawing dotted line around a rect (ie: dotted stroke)?

edited November 2015

Hi all. Is there any easy way to draw a dotted stroke? Just want to draw an empty rectangle (bar chart) with a dotted line around its borders (stroke), instead of solid. Don't see any easy way to do that. No shortcuts?

Tagged:

## Answers

• you need this :

https://www.processing.org/reference/lerp_.html

now write one function A (name it dottedLine)that can take two points and connect them with a dotted line (using `lerp`)

then write one function B that is called rectDotted which takes x,y,width and height and calls function A 4 times like

``````dottedLine (x,y,x+w,y); // upper line -
dottedLine (x,y,x,y+h);  // line left |
dottedLine (x+w,y,x+w,y+h); // line right |
dottedLine (x,y+h, x+w,y+h);           // lower line -
``````
• Ah, I see. Thanks. Very manual! Would be cool to have a strokeline('dotted') method built in, but this'll do just fine. Thx.

• An old thread but i came across it during a search, so other people must. Here is my solution (l = line in px, g = gap in px):

``````function dashedLine(x1, y1, x2, y2, l, g) {
var pc = dist(x1, y1, x2, y2) / 100;
var pcCount = 1;
var lPercent = gPercent = 0;
var currentPos = 0;
var xx1 = yy1 = xx2 = yy2 = 0;

while (int(pcCount * pc) < l) {
pcCount++
}
lPercent = pcCount;
pcCount = 1;
while (int(pcCount * pc) < g) {
pcCount++
}
gPercent = pcCount;

lPercent = lPercent / 100;
gPercent = gPercent / 100;
while (currentPos < 1) {
xx1 = lerp(x1, x2, currentPos);
yy1 = lerp(y1, y2, currentPos);
xx2 = lerp(x1, x2, currentPos + lPercent);
yy2 = lerp(y1, y2, currentPos + lPercent);
if (x1 > x2) {
if (xx2 < x2) {
xx2 = x2;
}
}
if (x1 < x2) {
if (xx2 > x2) {
xx2 = x2;
}
}
if (y1 > y2) {
if (yy2 < y2) {
yy2 = y2;
}
}
if (y1 < y2) {
if (yy2 > y2) {
yy2 = y2;
}
}

line(xx1, yy1, xx2, yy2);
currentPos = currentPos + lPercent + gPercent;
}
}

function dashedRect(x, y, w, h, l, g) {
dashedLine(x, y, x+w, y, l, g); //Top
dashedLine(x, y+h, x+w, y+h, l, g); //Bottom
dashedLine(x, y, x, y+h, l, g); //Left
dashedLine(x+w, y, x+w, y+h, l, g); //Right
}
``````
• @Gazzeh -- thank you -- could you please also edit your comment (gear icon) and format your code? (highligh, CTRL-o): https://forum.processing.org/two/discussion/15473/readme-how-to-format-code-and-text#latest

Also of interested, an open issue on dotted lines:

• @jeremydouglass - Thanks for the link i tried editing 4 times but couldn't get it. Done now

• @Gazzeh Thaxs for sharing.

@MirielLind Your line function would be very useful for this post after some minor modifications: https://forum.processing.org/two/discussion/comment/93734/#Comment_93734

Kf

Sign In or Register to comment.