Wednesday, March 26, 2008

Using and embedding fonts in Silverlight 2

There are multiple options to embed your fonts in Silverlight 2:

1. Using font as "Content"

First, embed the font as "Content" (see Properties, Build action). With this option, you can use the following method to set the font:

codesnippet1

The "problem" with this can be that the fontfile is embedded in the .XAP file. Therefore is available to anyone who wants to use the fontfile:

screenshot1

 

2. Using font as "Embedded Resource"

The advantage of using this method is that the fontfile is compiled with the DLL. So this makes it hard (maybe even impossible?) to retrieve the fontfile.
If it is still possible (maybe with a decompiler), at least it makes it less easy to get it.

When you want to use this method, first set the Build action to "Embedded Resource".

Next, use the following code to display the correct font (click to view larger size image):
 codesnippet2

 

3. Using font as a downloadable object

This has no real advantages to the above mentioned methods. Maybe if you use a font across multiple sites or something...

First, copy the font file to the ClientBin folder and use a WebClient to download the font:

codesnippet3

When the async request is completed, set the font:

codesnippet4 

That's it for now!

 

Download the source here

3 comments:

  1. You actually don't need to use the WebClient for the ClientBin option (or some of the others even). Silverlight 2 handles a lot of that for you as long as you use the fully qualified path (even an embedded resource could be used) to the font location using the file.ttf#fontname format.

    see: http://timheuer.com/blog/archive/2008/03/10/embedding-fonts-in-silverlight-2.aspx

    ReplyDelete
  2. Hi Tim,

    Thanks for that, didn't know it was possible to use Embedded Resources with the file.ttf#fontname format.
    I know it's not necessary to use the Webclient for downloading, but I wanted to mention it. The advantage of using webclient for this is that you can have preloading animation.

    ReplyDelete
  3. yes. this is possible "ttf#fontname"

    Initially, I also didn't know about this earlier so that I keep on telling people to use WebClient to download the custom font. Because I know it works and this is the way that we used in SL 1.1 but I came to know about using "ttf#fontname" from Silverlight forum. there are a few discussions about this topic in our forum..

    ReplyDelete