# Atalasoft Imaging SDK Development Blog

## Document Imaging and Developer Commentary

Blog Home RSS Feed Old Archive Atalasoft.com

# Dragon Curve

Posted by Steve Hawley

I was looking at the code for the Dragon Curve and it struck me that this should be an easy fractal to represent in PDF.  Even though the curve is usually represented with relative moves and turns which are trivial in PDF, I chose to stay closer to some of the examples in Rosetta Code to keep it consistent with their examples, if you wanted to side-by-side them.  This is a great basic example on how to use DotPdf for generating graphics on a page.

The first thing was a class that wraps the Dragon curve code.  There is one main entry that returns a PdfPath that represents the curve.  You could parameterize it further by exposing length and split.

public class Dragon

{

private static double _sqrt2 = Math.Sqrt(2.0);

private PdfPath _path;

private double _angle;

private PdfPoint _currPoint;

private void Turn(double degrees)

{

_angle += degrees * Math.PI / 180.0;

}

private void Forward(double length)

{

_currPoint = _currPoint + new PdfPoint(Math.Cos(_angle) * length, Math.Sin(_angle) * length);

_path.LineTo(_currPoint);

}

private void MakeDragon(double length, int split, double d)

{

if (split == 0)

{

Forward(length);

}

else {

length /= _sqrt2;

Turn(d * 45);

MakeDragon(length, split - 1, 1);

Turn(-d * 90);

MakeDragon(length, split - 1, -1);

Turn(d * 45);

}

}

public PdfPath MakeDragon(IPdfColor color, PdfPoint startLocation)

{

_angle = 0;

_currPoint = new PdfPoint(startLocation);

_path = new PdfPath(color, .75);

_path.MoveTo(_currPoint);

MakeDragon(400, 12, 1);

return _path;

}

}

All that remains is to use this class in the context of a PdfDocument.  First, I make a document,  then a page, then I place the output of the Dragon class on the page.  One thing you’ll note is that to make the page, I use the PdfDefaultPages class which is a set of factory properties each of which generates a new page in the size and orientation indicated by its name (I could’ve said eponymous size and orientation, but then I’d get a talking to about keeping my writing accessible.  Have I mentioned that I love language recently?).

static void Main(string[] args)

{

PdfGeneratedDocument doc = new PdfGeneratedDocument();

doc.EmbedGeneratedContent = false;

PdfGeneratedPage page = PdfDefaultPages.LetterLandscape;

Dragon dragon = new Dragon();

page.DrawingList.Add(dragon.MakeDragon(PdfColorFactory.FromRgb(.8, .25, .8), new PdfPoint(250, 250)));

doc.Save("dragon.pdf");

}

Seriously, that’s it.  It’s a nice short, sweet example.  Download DotPdf and run the code – you get a free trial!

Posted: 5/7/2012 2:46:56 PM by Steve Hawley | with 0 comments