Wednesday, May 29, 2013

WPF Effects and Blurry Fonts

I recently ran into a very strange bug that took me a while to figure out. I noticed that several buttons in my UI had blurry text. I thought I may have mistakenly changed the opacity or had some semi-transparent gradient overlaying the font that made it look so blurry. That did not turn out to be the case. After digging around a bit I found out what was causing the problem. It turns out that the problem was in my control template. I defined the button to have a border which contains a label inside it’s content. I applied the drop shadow to the outer border and was surprised to find that applying that effect to the border caused the contents of the border to become blurry. After a little research I found that using an effect causes the elements and all the sub-elements inside the control to be rendered into a Bitmap. When this happens, WPF cannot use ClearType rendering to display the text. This causes it to look blurrier than if there is not effect applied.

Here is what my buttons looked like with the drop shadow

image

And here is the same button without the drop shadow

image

To get around this bug simply place the text outside of the control that you will be applying the effect to.

<Border>
     <Border.Effect>
          …
     </Border.Effect>
     <TextBlock Text=”Blurry Text”/>
</Border>

//Change the code above to this.

<Grid>
     <Border>
          <Border.Effect>
                …
          </Border.Effect>
     </Border>

     <TextBlock Text=”Clear Text”/>
</Grid>

If you run into this issue, just change your code like what I did above and you should have clear text on your buttons even if you are using effects.

Happy Coding.