New WPF Features: Cached Composition

This is part of a series on New WPF Features 

One of the big improvements in 4.0 is the Cached Composition feature in graphics. This feature enables caching a live UIElement as a bitmap, which enables quick rendering of the element as a bitmap. The UIElement is user interactive and hence will respond to keyboard input, mouse clicks,… Also, transforms, effects,.. which operate on top will not cause the cache to regenerated resulting in better performance. Previously, it was common to use RenderTargetBitmap for this purpose. However, this would be at the cost of interactivity.

Lets jump into usage. You have the BitmapCache and the BitmapCacheBrush classes. The former is useful in rendering a complex UIElement while the latter facilitates better reuse of a cached element.

Usage of BitmapCache is shown below. RenderAtScale is helpful for zoom scenarios since it a cache which is multiple of the original bitmap size. Note that changing the UIElement subtree or these properties (EnableClearType\RenderAtScale) will cause the cache to be regenerated.

<Canvas.CacheMode>

    <BitmapCache EnableClearType="False" RenderAtScale="2"/>

</Canvas.CacheMode>

<Canvas CacheMode="BitmapCache"/>

 

BitmapCacheBrush is useful when you need to paint the same content on multiple elements. A sample usage is below.

<Grid.Resources>

    <Image x:Key="cachedImage" Source="Xaml.jpg" >

        <Image.CacheMode>

            <BitmapCache EnableClearType="False" RenderAtScale="1" SnapsToDevicePixels="False"  />

        </Image.CacheMode>

   </Image>

    <BitmapCacheBrush x:Key="cachedImageBrush" Target="{StaticResource cachedImage}" />

</Grid.Resources>

<Button Background="{StaticResource cachedImageBrush}" Content="Tile1" Grid.Column="1"/>

<Button Background="{StaticResource cachedImageBrush}" Content="Tile2" Grid.Column="2"/>

...

 

 Got a couple of apps in place to show the usage. The one on the left shows the zoom in action while the second app applies the cacheMode on Viewport2dVisual3D.

 The code is attached. Have fun

 

Share this post

 

CacheComposition2.zip