# Sierpinski Triangle - An Introduction into Silverlight by Example

By , 20 May 2007

Live Online Demo

## Introduction

"In the right light, at the right time, everything is extraordinary."
— Aaron Rose

### What is Silverlight?

"Silverlight is a cross-browser, cross-platform plug-in for delivering the next generation of Microsoft .NET–based media experiences and rich interactive applications for the Web."
http://silverlight.net/

This project is meant to provide some basic guidance on how to create your first Silverlight application. The topic is one of the most famous fractals in mathematics: Sierpinski Triangle. This should allow the reader to become familiar with both the basics of creating an application in Silverlight, and the basics of working with XAML objects both in files and programmatically through C#.

I always recommend building something like a "Hello World" application, when learning a new development platform. The Sierpinksi Triangle has just enough flavor to keep beginners interested without confusing the issue with unneeded complexity.

## Prerequisites

In order to create Silverlight applications you will need a machine, I recommend a virtual PC, and have it set up with the following Silverlight prerequisites:

• #### Runtimes

To get started with Silverlight, download the Silverlight 1.1 Alpha release to use .NET languages.

The runtime required to view Silverlight applications created with .NET Microsoft

• #### Developer Tools

The next generation development tool

• #### Microsoft Silverlight Tools Alpha for Visual Studio codename "Orcas" Beta 1 [download]

The add-on to create Silverlight applications using .NET

• #### Designer Tools

Professional design tool to create user interaction for Silverlight

• #### Software Development Kit

Download this SDK to create Silverlight Web experiences that target Silverlight 1.1 Alpha. The SDK contains documentation and samples.

## Background

Wikipedia.org Article: The Sierpinski triangle (fractal) [view]

"The Sierpinski triangle, also called the Sierpinski gasket, is a fractal named after Wac?aw Sierpi?ski who described it in 1915. Originally constructed as a curve, this is one of the basic examples of self-similar sets."

Sierpinski Triangle demonstrates the following features:

• how to work with polygons and points
• how to use brushes and colors
• how to work with backgrounds and images
• how to use the timer

## Using the code

Working with Silverlight means in a large part you will eventually have to work with XAML. A simple fractal like a Sierpinki Triangle is perfect opportunity to learn enough to become familiar with XAML, without being so demanding to have to learn everything about XAML first.

### Main Methods

#### drawSierpinskiTriangle()

This is the real work horse of the application. Part of the definition of a Sierpinski Triangle is that it is self similar. In other words a perfect candidate for recursion.

Basically we are taking sets of triangles with white borders, and randomly colored interiors and placing them on the canvas in a repeating recursive pattern.

```private void drawSierpinskiTriangle(int[] x, int[] y, int d)
{
// check to see if triangles are getting too small to render
if (d <= dMin)
{
// make a white color brush to draw our triangle borders with
m_brushStroke = new SolidColorBrush();
m_brushStroke.Color = Colors.White;

// make a random color brush to fill our triangles with
m_brushFill = new SolidColorBrush();
m_brushFill.Color = Color.FromRgb(
(byte)m_random.Next(255),
(byte)m_random.Next(255),
(byte)m_random.Next(255));

Polygon polygon = new Polygon();
polygon.Stroke = m_brushStroke;
polygon.Fill = m_brushFill;
polygon.StrokeThickness = .5;

// create a set of points
Point Point1 = new Point(x[0], y[0]);
Point Point2 = new Point(x[1], y[1]);
Point Point3 = new Point(x[2], y[2]);

// load our polygon with our calculated points
Point[] pointCollection = new Point[3];
pointCollection[0] = Point1;
pointCollection[1] = Point2;
pointCollection[2] = Point3;
polygon.Points = pointCollection;

// find out canvas to draw on
Canvas m_parentCanvas = (Canvas)this.FindName("parentCanvas");
m_parentCanvas.Children.Add(polygon);  // bottom of the recursion
}
else
{
// centers of the sides:
int xMc = (x[0] + x[1]) / 2, yMc = (y[0] + y[1]) / 2;
int xMb = (x[0] + x[2]) / 2, yMb = (y[0] + y[2]) / 2;
int xMa = (x[1] + x[2]) / 2, yMa = (y[1] + y[2]) / 2;

int[] xNew1 = { x[0], xMc, xMb };
int[] yNew1 = { y[0], yMc, yMb };
drawSierpinskiTriangle(xNew1, yNew1, d / 2);    // recursion

int[] xNew2 = { x[1], xMc, xMa };
int[] yNew2 = { y[1], yMc, yMa };
drawSierpinskiTriangle(xNew2, yNew2, d / 2);    // recursion

int[] xNew3 = { x[2], xMb, xMa };
int[] yNew3 = { y[2], yMb, yMa };
drawSierpinskiTriangle(xNew3, yNew3, d / 2);    // recursion
}
}
```

This method handles all of the initialization of the fractal's variables. It starts the recursion, and kicks off a timer that will handle randomizing the triangle's background colors once the fractal is done drawing.

```public void Page_Loaded(object o, EventArgs e) {
// Required to initialize variables
InitializeComponent();

int d = 512;    // basis (width of the triangle)
int x0 = 0;     // distance from the left
int y0 = 0;     // distance from the top
int h = (int)(d * Math.Sqrt(3) / 2);    // height
// so: suitable for an equilateral triangle
int xA = x0, yA = y0 + h;        // (bottom-left)
int xB = x0 + d, yB = y0 + h;    // (bottom-right)
int xC = x0 + d / 2, yC = y0;    // equilateral triangle (top-center)
int[] x = { xA, xB, xC };
int[] y = { yA, yB, yC };

drawSierpinskiTriangle(x, y, d / 2);     // start recursion

// timer tick will handle animating triangle background colors
System.Windows.Browser.HtmlTimer timer =
new System.Windows.Browser.HtmlTimer();
timer.Interval = 50;
timer.Enabled = true;
timer.Tick += new EventHandler(timer_Tick);
}    ```

#### timer_Tick()

This event will be on a timer once the fractal recursion is completed. It's job is to create a new random color brush, then choose a random triangle and fill its interior with the new color. This is completely a cosmetic effect, just something to give the demo a little color, literally.

```void timer_Tick(object sender, EventArgs e)
{
m_brushFill = new SolidColorBrush();
m_brushFill.Color = Color.FromRgb(
(byte)m_random.Next(255),
(byte)m_random.Next(255),
(byte)m_random.Next(255));

Canvas m_parentCanvas = (Canvas)this.FindName("parentCanvas");

int childIndex = m_random.Next(m_parentCanvas.Children.Count);
if(childIndex > 2)
((Polygon)m_parentCanvas.Children[childIndex]).Fill = m_brushFill;
}
```

## Tips & Tricks

### Browser.HtmlTimer

I found there is an `HtmlTimer `class in Silverlight 1.1. This class is undocumented and marked obsolete.

Visual Studio shows a warning after compilation: `'System.Windows.Browser.HtmlTimer`' is obsolete: 'This is not a high resolution timer and is not suitable for short-interval animations. A new timer type will be available in a future release.

## Points of Interest

One thing you might notice is that we are always recreating our brush objects, and that we are never reusing any of them. This is because in Silverlight 1.1 Alpha, at least, you can only use a brush on one object. It will generate an exception if you attempt to reuse it again.

Be sure to check out the timer code using `System.Windows.Browser.HtmlTimer`, for now, it is the easiest way to do draw animations.

## History

• 2007.05.20 - Uploaded original article

A list of licenses authors might use can be found here

 CJCraft.com Web Developer United States Member
No Biography provided

Votes of 3 or less require a comment

 Search this forum Profile popups    Spacing RelaxedCompactTight   Noise Very HighHighMediumLowVery Low   Layout Open AllThread ViewNo JavascriptPreview   Per page 102550
 First Prev Next
 Silverlight plugin Ashley van Gerven 22 May '07 - 1:35
 Just wondering if the Silverlight plugin requires .NET framework to function? The download is only 4.24MB - does it have any .NET functionality embeded or does it require .NET 3.0 to support WPF/WCF?   "For fifty bucks I'd put my face in their soup and blow." - George Costanza CP article: SmartPager - a Flickr-style pager control with go-to-page popup layer. Sign In·View Thread·Permalink
 Re: Silverlight plugin uluhonolulu 27 May '07 - 23:24
 Re: Silverlight plugin Judah Himango 31 May '07 - 5:26
 The Silverlight 1.1 does require the .NET framework, however, it requires a slimmed down, 4MB .NET framework. This framework has many of the standard APIs you'd expect in the threading namespace, the standard types, etc. However it doesn't have any Windows Forms controls, WPF controls, and I don't believe it has anything from System.Drawing namespace. System.Management, Enterprise Services, etc. are all gone from the Silverlight version of the .NET framework, thus making it a small download.   Tech, life, family, faith: Give me a visit. I'm currently blogging about: Trekkie love The apostle Paul, modernly speaking: Epistles of Paul   Judah Himango Sign In·View Thread·Permalink
 Re: Silverlight plugin Ashley van Gerven 31 May '07 - 13:41
 OK, so you couldn't use it to build a form to accept user input etc? You would build the form in HTML and then send it to Silverlight object to send to a WCF service for example?   "For fifty bucks I'd put my face in their soup and blow." - George Costanza CP article: SmartPager - a Flickr-style pager control with go-to-page popup layer. Sign In·View Thread·Permalink
 Re: Silverlight plugin Judah Himango 31 May '07 - 16:05
 I believe it's possible to build WPF controls from the primitives provided in Silverlight, although I can't say for sure. WPF controls weren't built-in probably to keep the download small.   In any case, one could simply use standard HTML controls where applicable.   Tech, life, family, faith: Give me a visit. I'm currently blogging about: Repentance The apostle Paul, modernly speaking: Epistles of Paul   Judah Himango Sign In·View Thread·Permalink
 [Message Deleted] The Grand Negus 20 May '07 - 18:42
 Re: Am I the only one who has a problem with this? Davide Icardi 20 May '07 - 23:04
 Hi,   Consider that you need the previous software if you want to create silverlight application. Actually I think that some software are optional also for the developer.   To just see the demo in your browser you just need to install "Microsoft Silverlight 1.1 Alpha" for you specific browser (IE, Firefox) and platform (Win, Mac).   I'm not an expert on Silverlight I don't known about the problem of the timer or of the brush but I think that Silverlight idea is quite good (and powerful) and consider that for now is only an Alpha release.   Davide Sign In·View Thread·Permalink
 Re: Am I the only one who has a problem with this? CJCraft.com 21 May '07 - 2:23
 You have some good points. But here are some things to consider.   The download set is large because it covers three areas: developer, designer, and end user. If you consider Visual Studio to be like Adobe Flash, and Expression Blend to be like Photoshop, and the Silverlight plugin to be like the Flash plugin, then things are more reasonable.   On release I imagine there will just be Visual Studio, Expression Blend, and the Silverlight Plugin.   The limited timer support is solely related to being an alpha release.   Limited brush support is also related to being an alpha release.   I don't see Silverlight as being the perfect solution, but I do think it *will* be a good solution. And I do think it is definitely a step in the right direction. Sign In·View Thread·Permalink
 [Message Deleted] The Grand Negus 21 May '07 - 6:28
 Re: Am I the only one who has a problem with this? jmw 21 May '07 - 10:59
 The Grand Negus wrote:One would think that the basis for such grand things would be, well, built-in.   How do you "build in" retroactively? Silverlight, like Flash, harnesses the existing install base of browsers. If they offered a technology that replaced the browser then a) it wouldn't be widely deployed for at least the next 5 years and b) It wouldn't integrate as seamlessly with web pages.   The Grand Negus wrote:Their "alpha" releases should not have omissions and design flaws of this nature.   Alpha releases, by nature, are technology previews. They have been gracious enough to let us have a sneak peak at *what is in development*. This is not something that has to necessarily even be usable, it is purely an opportunity for us to see where things are heading, and offer some feedback to make the final product even better. If you don't want alpha quality code, then wait for the beta, or better still wait for the release! Sign In·View Thread·Permalink
 Re: Am I the only one who has a problem with this? Paul Tallett 21 May '07 - 20:51
 If you want "built-in" write a WPF XBAP which provides a full next-generation environment built-right in to the browser.   You can write Silverlight apps with the 2MB plugin and Notepad if you like. The toolset is just there to make your life easier. I'd add the Blend 2.0 beta to that list too so you can do WYSIWYG design.   Personally I'm quite surprised how functional 1.1 is, considering 1.0 is still in beta. Usually when something is in beta you don't get alpha's of the next version to play with. You can actually develop something meaningful with 1.1 and deploy it to the web (admittedly without Microsoft support). Most Alphas I've seen in the past have serious restrictions and omissions (you know, the parts they are still developing).   Cheers, Paul Sign In·View Thread·Permalink
 Re: Am I the only one who has a problem with this? eggsovereasy 24 May '07 - 8:13
 The Grand Negus wrote:Microsoft has been in the software business long enough to know better. Their "alpha" releases should not have omissions and design flaws of this nature. It makes me think they've got the newbies working on the "next generation" stuff, not the pros!   If it did not have omissions and design flaws it would be a Release Candidate not an alpha. Sign In·View Thread·Permalink
 Re: Am I the only one who has a problem with this? eggsovereasy 24 May '07 - 10:18
 I don't know, to me alpha means "it works, for the most part" things are ugly and slow. Beta is where you should have all your features implemented, but still buggy. If this were a beta I would be worried. Sign In·View Thread·Permalink
 Re: Am I the only one who has a problem with this? Ward 21 May '07 - 21:08
 If you just want to play arround with Silverlight, installing the plugin 'Microsoft Silverlight 1.1 Alpha' is enough. With this you can view all demo animations. If you want to create your own graphics and animations you can simply use notepad or any other texteditor. An example tutorial can be found here: http://dotnetslackers.com/articles/silverlight/SilverlightFirstStepsAnalogClock.aspx[^]     Ward Sign In·View Thread·Permalink
 Some confusion blumenhause 20 May '07 - 18:30
 Re: Some confusion CJCraft.com 21 May '07 - 2:15
 Sure, now that you mention it, that might make a great article in and of itself.   Here's the elevator pitch:   "Silverlight provides a unified programming model for building Windows smart client user experiences that incorporate UI, media, and documents. Using Visual Studio, Microsoft Expression and XAML, you can increase developer-designer productivity."   Basically Silverlight allows developers to use .NET languages like C# and Visual Basic .NET, along with XAML to create "user experiences" that will work on Safari (Apple), Opera, Firefox, and Internet Explore, and soon Windows Mobile. There is effort underway to allow Silverlight to run on Mono, Linux.   So at first look, Silverlight competes with Flash, but it is meant to be more than that. End goal I would think is to make Web application possibilities equal or greater than desktop possibilities. Sign In·View Thread·Permalink
 Re: Some confusion TerryD64 22 May '07 - 5:54
 Last Visit: 31 Dec '99 - 18:00     Last Update: 25 May '13 - 10:52 Refresh 1

Web02 | 2.6.130523.1 | Last Updated 20 May 2007