Archive for the ‘Tutorials’ Category

Using FluidMoveBehavior to animate grid coordinates in Silverlight

May 13, 2010 6 comments

At the Chicago .toolbox event last week, @thejeanious asked how she could easily animate an object between grid row and columns.

l originally answered with something like “I would use a Canvas and figure out the XY positioning…”, but after she explained she was working on a game where the grid seemed to be a natural fit, we came up with a different solution – the new FluidMoveBehavior that comes with Expression Blend 4.

I’ve been explaining the concept of Fluid UI, as a means to animate discrete properties.  The first example that comes to mind is the Visibility property of an element.  Its either Visible or Collapsed, there is no way to interpolate between the two values. When you change the Visibility property between different VisualStates and check the “Use Fluid UI” button, rather than instantly disappearing, Fluid UI will animate the opacity and scale transform to provide a visual transition between the discrete values.

This type of behavior works with Grid Row and Column positioning as well. If you attach the FluidMoveBehavior to a Grid and set AppliesTo to “Children”, and then at run-time change the Grid Row and Column properties of an element, the item will animate to its new position.

I’ve created a quick sample that demonstrates this behavior.

Run the Fluid Checkerboard

  • Click a rectangle and the ball will animate to that rectangle’s position in the grid
  • The cursor keys are also hooked up to move the ball

Download the source code


The beauty of this sample is that shows by quickly applying the FluidMoveBehavior I can animate the position of an element (with easing) writing very little code.

WTF Step by Step guide to installing Silverlight Tools

April 28, 2010 6 comments

With Silverlight 4 shipping and Expression Blend 4 RC made available, now was a great time to update the Flash to Silverlight section on the Project Rosetta site.

My main goal was to update the Getting Started series to take advantage of new version 4 features.  I also took advantage of this update to greatly improve the Installation and Setup tutorial.

The content for the site is made for those with an interest in experimenting with Silverlight, who most likely do not have any .NET development experience or in some cases, even Windows.

As a first step, configuring your design and development environment for Silverlight can be a little daunting. Happily the installation process is now much simpler with the advent of the version 4 tools.

Nonetheless, as requested, I’ve put together a simple step by step walkthrough of the install process.

Working towards more Silverlight time and less “WTF?” time.

The new Setup tutorial takes full advantage of the Web Platform Installer (Web PI) which acts as a download and install tool for the needed Tools.  This makes writing the tutorial and installing much easier.

Along with the step by step guide, I’ve also updated the Getting Started series to reflect the new v4 tools and features, specifically CompositionTarget.Rendering (which is like ENTER_FRAME) and CompositeTransform (which makes transforms simpler than before).

Next month, we’ll be updating the Flash to Silverlight site with a new set of tutorials focused on Media (codecs, players, markers, etc) and how it compares to Flash media.

Now for some Taco Bell…

Avatar Mosaic -Experimenting with the Artefact Animator

April 21, 2010 6 comments

Avatar Mosaic Screenshot

After finding out about the Artefact Animator,  written by Jesse Graupmann, I knew I wanted to try it out.

The Artefact Animator library is based on the same concept as Tweener for Flash, which provides an easy way to do procedural animations in WPF and Silverlight.

I found some time last night to put together this little Xbox Live avatar mosaic and was very pleased with the results.

Test the Avatar Mosaic Prototype

Download the Source

If you take a look at the prototype, you can see there’s a few things you can do:

  • Drag the grid splitter, resize the window or change the padding slider to cause the tiles to reposition.
  • Type a new Xbox Live Gamertag in the textbox and TAB out to cause the tiles to fade out and fade back in with a new image
  • Roll over a tile and it will scale down until you roll off of it

You can download the source to see the full code but I’ll just highlight the areas where the Artefact Animator is used below.

Download the Library

The first thing you need to do is download a copy of the library from the codeplex site. Jesse has also posted documentation which will help you understand how to use the library. Once you have the library downloaded make sure to add a reference to your project.

Position the Avatar Tiles

When the application loads, AvatarTile controls are dynamically added to the main Canvas called LayoutRoot. Once the SizeChanged event of the Canvas is fired the updateTileLayout method is called.  Calling the method at this point ensures the ActualWidth property of the Canvas is available and the tile layout will be repositioned if the browser window is resized or the grid splitter is moved.

Then we loop through the children of the Canvas and based on the index of the tile an easing function is added using the code below:

ArtefactAnimator.AddEase(element, AnimationTypes.X, curX, time, ease, delay);
ArtefactAnimator.AddEase(element, AnimationTypes.Y, curY, time, ease, delay);

The element parameter defines which AvatarTile to animate.

AnimationTypes is an enum tied to different properties you can choose to animate.

The curX and curY parameters define the new value of the animated property.

The time parameter defines how long the animation should take to get to the new value.

The delay parameter defines how long before the animation should begin.

The ease parameter is a PercentHandler class instance used to define the type of easing function.  The full list of Ease Functions is posted, along with how to create custom ease functions.

When determining the curX and curY values in the updateTileLayout method, padding is also taken into consideration.  The slider sets the padding based on its position.  After the slider is moved, the updateTileLayout method is called to reflect the change in padding.

Fade Out, New Image, Fade In

After a new value is entered into the textbox and the LostFocus event is fired, the AvatarTiles are faded out to reset the brush. This was a test of the available Events of the EaseObject.

//fade out each tile incrementally
for (int i = 0; i < tileCount; i++)
   easeObject = ArtefactAnimator.AddEase(element, AnimationTypes.AutoAlpha, 0,
                                            time, ease, delay); 
   delay += .05;

//capture completed event of last "fade out" easing
easeObject.Complete += new EaseObjectHandler(easeObject_Complete);

After looping through the children and animating the Opacity of each element, a reference to the return value of the AddEase method is stored. This way we can add an event handler to the Completed event of the EaseObject instance. The event handler will then reset the image brush and animate the tiles back into view using the code below:

//set brush to new image based on textbox
ImageBrush ib = Application.Current.Resources["xboxTileBrush"] as ImageBrush;
ib.ImageSource = new BitmapImage(new Uri(string.Format("{0}/avatarpic-l.png", gamerTagTextBox.Text)));

//fade in each tile incrementally
for (int i = 0; i < tileCount; i++)
    ArtefactAnimator.AddEase(element, AnimationTypes.AutoAlpha, 1,
                                time, ease, delay);
    delay += .05;

Avatar Mosaic Screenshot

Mouse over action for the Tiles

And finally, taking advantage of some of the Shortcut functions built in, we’ll scale the AvatarTile based on the mouse over events.  In the AvatarTile class, the first step is to use the handy NormalizeTransformGroup method which ensures the needed Transform objects are in place.

Once the library is upgraded to Silverlight 4, this step could become obsolete by leveraging the new CompositeTransform class.

In the Loaded event:

LayoutRoot.RenderTransformOrigin = new Point(.5, .5);

Then on Mouse Enter:

LayoutRoot.ScaleTo(.5, .5, .8, AnimationTransitions.ElasticEaseOut, 0);

And to remove the effect on Mouse Leave:

LayoutRoot.ScaleTo(1, 1, .8, AnimationTransitions.ElasticEaseIn, 0);

And that’s it! Everything is hooked up and ready to run.

Final Thoughts

I really like the direction Jesse is headed with the library by making procedural animations easier to write in Silverlight and WPF.  He’s mentioned the library is in its early stages and would love to see more people use it and provide feedback.

One of the things I found is that after changing the gamertag and fading out the tiles, the repositioning animations got very slow.  I’m not sure if that’s colliding easing objects or what, but there’s some performance work that could be done there.

The other issue is that due to the nature of procedural animations there is no design-time experience.  The best thing about Storyboards is that you can create them visually in Blend and preview them without having to run the application.  It’d be interesting to see if there was some way to tackle this problem. Not sure what to suggest yet.

Test the Avatar Mosaic Prototype

Download the Source

What do you think? Give the Artefact Animator a try and send your feedback to Jesse.

Expression Blend 4 Beta Feature Overview available for download

March 15, 2010 15 comments

Expression Blend 4 Beta Overview

Expression Blend 4 Beta is out in the wild and available for download! As a companion whitepaper, check out the Expression Blend 4 Beta Feature Overview which provides a walkthrough of the new features. Here’s where we begin:


Expression Blend 4 Beta adds support for Silverlight 4 and Windows Presentation Foundation 4, while maintaining the ability to create and edit Silverlight 3 and WPF 3.5 with Service Pack 1(SP1) applications. Interoperability with Visual Studio 2010 has been added, maintaining the seamless workflow between the two tools.

In response to customers’ desires to do more without code, new features in SketchFlow enable more dynamic prototypes to be created and provide an enhanced player experience. Additionally, Expression Blend 4 Beta adds powerful new behaviors for all application types and makes them configurable with conditional statements.

Expression Blend 4 Beta introduces new features that support the Model-View-ViewModel (MVVM) pattern for business application development. New design-time data and resource features, along with behaviors such as CallMethodAction and InvokeCommandAction greatly increase the capability and experience for design tasks while building these applications.

Along with these three areas of focus, other additions include: new controls, such as the PathListBox, new pixel shader effects, transition effects and helpful tooling improvements.

Expression Blend 4 Beta is an exciting update that continues to revolutionize the speed and efficiency with which you can take your ideas from concept to completion on the Silverlight and .NET platforms.


The rest of the paper is divided into the following topics:

  • SketchFlow Improvements for Better Prototypes
  • Enabling Business Application Development with MVVM
  • New Controls and Effects for Dynamic Interfaces
  • More Interactivity and Less Code with New Behaviors
  • Editor and Tooling Improvements
  • and Expression Blend Resources

I hope you find the Expression Blend 4 Beta Feature Overview useful and that you share your feedback. We want to make sure the overview for the final release is even better!

Big update for the Project Rosetta site today

March 3, 2010 3 comments

We just shipped a major update to the Project Rosetta site, including a new a series of Flash to Silverlight tutorials, an updated API Guide with a quick reference list and a full list of recommended tools, code samples and frameworks to download.

Getting Started Series: Project Rosetta site update

API Guide:

And this is just the beginning – you can look forward to new tutorials in the Getting Started series, along with new series of tutorials that go deeper into a single topic.

To keep track of the latest Project Rosetta content and other similar tutorials Follow us on Twitter or get updates via our RSS Feed.

Gesturecons – icons for prototyping Multi-touch applications

February 22, 2010 9 comments

Gesturecons mapped to Windows Touch API

Gesturecons is a set of wire-framing gestural icons created by Ryan Lee, a designer for Cynergy. The icons are available for download made available via a Creative Commons License.

These icons will be very useful when creating wireframes or tutorials covering touch gestures. As a Silverlight and Windows developer, I wanted to see how well these fit with the Windows Touch API.  In the image to the right, I’ve mapped the icons to the Windows Touch Gestures. (Click the image to see it larger)

Importing the Gesturecons into Expression Blend to use in an application or a SketchFlow prototype is simple since Ryan has provided the icons in an Illustrator format.

To import the icons into Blend, follow these steps:

  1. Create a new or open an existing project
  2. Select File > Import Adobe Illustrator File…
  3. In the dialog select the “” file from the “” file
  4. The artwork will appear in your UserControl in a Canvas named cs
  5. Zoom out the artboard to see all of the icons by: typing Ctrl+-, using the mouse wheel over the artboard or using the Zoom dropdown in the bottom left corner
  6. In the Objects Panel, Delete the borders Canvas
  7. Right-click the icons Canvas and select Ungroup
  8. Select the first Path, scroll down to the last Path and holding Shift select the last Path
  9. With all of the Paths selected now, scale down the group of icons by dragging one of the corners of the outermost bounding box, hold Shift to lock to a relative scale.
  10. Reposition the group to fit on your UserControl and zoom back out to 100%
  11. To reset the cs Canvas, in the Properties Panel, set Width and Height to Auto

The Gesturecons are now available in XAML as reusable vector paths. The next steps you might take to make these easier to reuse include, grouping Paths that make up an individual icon and making them available as Resources.

Thanks again to Ryan Lee for creating and sharing the Gesturecons!

New tutorials page aggregating recent work, 34 for launch

February 16, 2010 2 comments

Writing tutorials

I’ve done a few events recently and two of the topics that come up when talking to attendees include additional resources for learning and tutorials that I’ve written myself that that demonstrate a technique they’re asking about.

I’ve been keeping track of my favorite resource here on this Additional Resources page, which includes learning resources and a list of Microsoft and Community people to follow via their blogs or twitter.

One thing I did not have, though, was a list of all the tutorials and labs that I’ve written.

So, I’ve put together a new Tutorials page that lists all of the recent Silverlight 3, Expression Blend 3 and Silverlight 4 Beta tutorials and labs I’ve been worked on. This will be helpful for me when trying to refer back to past content, and hopefully it will be useful for you as well in case something in there address or introduces you to a new concept.

I have a list of 34 pieces of content to start with, but my current queue of tutorials includes 11 more ideas in the works. There are plenty more ideas in my head, though, so I’m going to set a goal of 60 by the end of June.

As a big fan of graphics, UI work and Blend, I will likely be focusing there.  Certainly one of the most requested topics lately is skinning controls and application themes.

What do you want to learn about?

Flash to Silverlight Guide – Graphics, Images and Display List

January 15, 2010 3 comments

movieclip guy in action

The second edition of the Flash to Silverlight Guide has been posted!

This edition includes new sections on Graphics and Images and Displaying Objects, as well as a bit of a facelift to the site.

Some of the previous feedback included:

“I wish I would have this when I first started on Silverlight”

– Perfect, we’re hoping to help people just getting started.

“There’s a lot of information on the pages, but its pretty dry.”

– Totally agreed.  So along with other graphics and code samples, I spent some time putting together scenes of the new “movieclip guy” acting out the different properties. Not only does this decrease the dryness and encyclopedia-ish nature of the guide, the icons can also act as quick visual hints.

One of my favorite parts about the artwork is that it comes from a group of assets for a new site that is in the works. Unfortunately I can’t share anything about the site just yet, but I did get the ok to preview the graphics. And the site is going to rock.

Anyways, enough about the graphics, enjoy the Guide.  Next on the list are the Animation, Code techniques and Out of Browser sections.

Converting Hexadecimals to Colors in code for Silverlight

January 14, 2010 10 comments

Coming from other platforms like HTML, CSS, JavaScript and Flash you will be used to defining colors with hexadecimal values.  Silverlight does support the use of hexadecimal values in XAML, in fact it supports 4 different formats (rgb, argb, rrggbb and aarrggbb). These values are then converted using a special type converter during the parsing of the XAML file.  A string value of #000 is converted into a Color structure that will render black as expected.

Unfortunately this type conversion is not readily accessible when working in code.  In code there are two options built-in, the FromArgb method and system-defined colors.

//using the FromArgb method 
ellipse.Fill = new SolidColorBrush (Color.FromArgb(255, 29, 177, 0));

//using a system-defined color 
ellipse.Fill = new SolidColorBrush (Colors.Green);

As a fan of defining colors using hexadecimals, like myself, you may find switching to bytes in code bothersome. Happily we can do something about this.

The code sample below converts an unsigned integer, which can be written in hexadecimal format, into a Color structure.  Not only are we avoiding string parsing by using the uint type and bitwise operators, we’re also taking advantage of extension methods in C#. This allows us to extend the uint type and reuse this method anywhere in code that has a reference to our ColorExtensions class.

//extensions must be defined in a non-generic static class
public static class ColorExtensions
   public static Color ToColor(this uint argb)
      return Color.FromArgb((byte)((argb & -16777216) >> 0x18),
                            (byte)((argb & 0xff0000) >> 0x10),
                            (byte)((argb & 0xff00) >> 8),
                            (byte)(argb & 0xff));

//sample usage within a different class
ellipse.Fill = new SolidColorBrush (0xFF1DB100.ToColor());

And that’s it! You can now define color values using hexadecimal in your XAML and C# code.

(If you’re new to Silverlight and want to learn more about the SolidColorBrush class referenced and Brushes in general, check out the Brushes in Silverlight documentation.)

Image Blitting in Silverlight with WriteableBitmapEx

January 9, 2010 13 comments

During a conversation with Jesse Freeman, AKA the Flash Bum, he directed me to one of his tutorials on image composition with Flash. The tutorial, called Create Random Torn Photos with Actionscript 3.0, demonstrates a very cool way to dynamically apply a torn weathered effect to a photo.


The question then came into play – can you do this in Silverlight?

The answer – yes, yes you can.

Let me explain how I was able to accomplish the same effect.

In Silverlight, the WriteableBitmap class is used to manipulate bitmap data. The current class is pretty low-level, providing access to the bits, but not many convenience features. Thankfully a few community members have started an open source library called WriteableBitmapEx. This library extends the functionality of the WritableBitmap class to include methods for drawing, blending and more.

This was a great start, but for this project two blend modes were missing – Mask and Multiply. I spent a little time implementing the new Blend modes and have since checked them back into the project.  (Thanks go to René Schulte for then optimizing and formatting the code)

With the right pieces in place now came the simple process of compositing. The first step was to randomly select one of the skins and load the separate parts of the skin along with the photo:

//randomly select a skin
Random r = new Random();
int skinNum = r.Next(1, 7);
string base_url = string.Concat("/TornPhotoDemo;component/images/skin", skinNum);

//load the different parts of the skin, using a helper method 
WriteableBitmap maskBmp = LoadBitmap(base_url + "/photo_mask.png");
WriteableBitmap textureBmp = LoadBitmap(base_url + "/photo_texture.jpg");
WriteableBitmap edges_maskBmp = LoadBitmap(base_url + "/photo_edges_mask.png");

//load the photo
WriteableBitmap bmp = LoadBitmap(base_url + "/photo.jpg");

photo loaded

Then using the extension method Blit and the new BlendMode, use “photo_mask.png” to mask the photo. Effectively replacing the alpha of each pixel in “photo.jpg” yet keeping the color data.

//mask the photo
bmp.Blit(cRect, maskBmp, cRect, WriteableBitmapExtensions.BlendMode.Mask);

photo masked

Then using the same Blit method and the other new Blend Mode, multiply the color values of the photo and the “photo_texture.jpg”.  This darkens the colors and adds the crumpled effect.

//apply the multiply effect to the photo with the texture image (3 times)
bmp.Blit(cRect, textureBmp, cRect, WriteableBitmapExtensions.BlendMode.Multiply);
bmp.Blit(cRect, textureBmp, cRect, WriteableBitmapExtensions.BlendMode.Multiply);
bmp.Blit(cRect, textureBmp, cRect, WriteableBitmapExtensions.BlendMode.Multiply);

photo multiplied with texture 3 times

For more wear and tear, a ripped edges bitmap is created using “photo_texture.jpg” as the base. A different mask image “photo_edges_mask.png” is used to then cut it down to a few edges.

//use the texture as the base for the torn edges
edgesBmp.Blit(cRect, textureBmp, cRect, WriteableBitmapExtensions.BlendMode.None);
edgesBmp.Blit(cRect, edges_maskBmp, cRect, WriteableBitmapExtensions.BlendMode.Mask);

edges created

Now its time to use the AlphaBlend mode to then blit the edges bitmap and the crumpled photo bitmap together.  The photo mask is then run again to ensure the edges to run over the originally masked size.

//alpha blend the edges onto the mask
bmp.Blit(cRect, edgesBmp, cRect, WriteableBitmapExtensions.BlendMode.AlphaBlend);
//mask the photo again
bmp.Blit(cRect, maskBmp, cRect, WriteableBitmapExtensions.BlendMode.Mask);

photo blended with edges

And there you have it a randomly torn photo created dynamically in code. One of the things pointed out by Jesse is at the end of tutorial is the file sizes.  Saved off by itself the image above was 478k, individually the plain photo and the skin parts equal 104k. That’s 374k less memory and its dynamically generated. That’s kick-ass.

Thanks to Jesse for the concept and code and thanks to the WritableBitmapEx team for their work.

Download the TornPhotoDemo source

Run the live TornPhotoMaker lab