Skip to content

Instantly share code, notes, and snippets.

@alecmce
Created October 3, 2010 20:48
Show Gist options
  • Save alecmce/608921 to your computer and use it in GitHub Desktop.
Save alecmce/608921 to your computer and use it in GitHub Desktop.
package alecmce.ui.misc
{
import flash.display.Graphics;
import flash.display.GraphicsPath;
import flash.geom.Rectangle;
public class Scribble
{
public var spacing:Number;
public var thickness:Number;
public var scaleUp:Number;
public function Scribble(thickness:Number, spacing:Number, scale:Number)
{
this.thickness = thickness;
this.spacing = spacing;
this.scaleUp = scale;
}
public function draw(graphics:Graphics, rect:Rectangle):void
{
var path:GraphicsPath = generatePath(rect);
graphics.lineStyle(thickness, 0);
graphics.drawPath(path.commands, path.data);
}
private function generatePath(rect:Rectangle):GraphicsPath
{
var path:GraphicsPath = new GraphicsPath();
var left:int = rect.left;
var top:int = rect.top;
var height:int = rect.height;
var width:int = rect.width;
var right:int = rect.right;
var bottom:int = rect.bottom;
var dTop:int = width;
var dRight:int = 0;
var dBottom:int = width;
var dLeft:int = 0;
var swap:Boolean = Math.random() < .5;
var onTop:Boolean = true;
var onRight:Boolean = true;
var oldX:int;
var oldY:int;
var controlX:int;
var controlY:int;
var newX:int;
var newY:int;
var scalar:Number = spacing;
if (swap)
{
dTop -= scalar;
oldX = left + dTop;
oldY = top;
path.moveTo(oldX, oldY);
}
else
{
dRight += scalar;
oldX = right;
oldY = top + dRight;
path.moveTo(oldX, oldY);
}
var isOngoing:Boolean = true;
while (isOngoing)
{
swap = !swap;
if (swap)
{
if (onTop)
{
dTop -= scalar;
if (dTop > 0)
{
newX = left + dTop;
newY = top;
}
else
{
dLeft -= dTop;
newX = left;
newY = top + dLeft;
onTop = false;
}
}
else
{
dLeft += scalar;
newX = left;
newY = top + dLeft;
isOngoing = dLeft < height;
}
}
else
{
if (onRight)
{
dRight += scalar;
if (dRight < height)
{
newX = right;
newY = top + dRight;
}
else
{
dBottom -= (dRight - height);
newX = left + dBottom;
newY = bottom;
onRight = false;
}
}
else
{
dBottom -= scalar;
newX = left + dBottom;
newY = bottom;
isOngoing = dBottom > 0;
}
}
var dX:Number = (newX - oldX);
var dY:Number = (newY - oldY);
if (swap)
{
controlX = oldX + dX * .5 - dY * .09;
controlY = oldY + dY * .5 + dX * .09;
}
else
{
controlX = oldX + dX * .5 + dY * .1;
controlY = oldY + dY * .5 - dX * .1;
}
oldX = newX;
oldY = newY;
if (isOngoing)
path.curveTo(controlX, controlY, newX, newY);
if (onTop && onRight)
scalar *= scaleUp;
else if (!onTop && !onRight)
scalar /= scaleUp;
if (scalar < spacing)
scalar = spacing;
}
return path;
}
}
}
@alecmce
Copy link
Author

alecmce commented Oct 3, 2010

So I thought about exploding out the generatePath function into a lot of sub-methods, but honestly, I don't think this is too hard to read.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment