Introduction
A while ago, I wrote a tip on how to create a tiled background for Windows store apps.
I remember the first thing I tried was to subclass the Brush
class, but I couldn’t do anything to replicate the WPF’s TileBrush
behavior. So I’ve essentially ended up creating a large bitmap based on the provided image template. It was good enough as a workaround, but aside from performance issues, the thing that was bugging me the most was that I couldn’t use it as a brush. Since then, a lot things have changed, we got the Win2D framework and later the Composition
API, so it’s about time to rewrite that code. ;)
Background
To be completely honest, I really had no need to tile something, but I was working on a project with composition API and I stumbled upon this:
And of course, I remembered how I struggled to subclass the damn brush to achieve tiling. So I opened up another instance of VS and this is what I ended up with:
var surface = LoadedImageSurface.StartLoadFromUri(ImageSourceUri);
var surfaceBrush = Compositor.CreateSurfaceBrush(surface);
surfaceBrush.Stretch = CompositionStretch.None;
var borderEffect = new BorderEffect()
{
Source = new CompositionEffectSourceParameter("source"),
ExtendX = Microsoft.Graphics.Canvas.CanvasEdgeBehavior.Wrap,
ExtendY = Microsoft.Graphics.Canvas.CanvasEdgeBehavior.Wrap
};
var borderEffectFactory = Compositor.CreateEffectFactory(borderEffect);
var borderEffectBrush = borderEffectFactory.CreateBrush();
borderEffectBrush.SetSourceParameter("source", surfaceBrush);
Yup, that is all you need to create a tiled brush in UWP with Composition API and Win2D. The attached source code is a bit refactored to support image source change, but it's basically identical...
And in XAML, you use it as standard brush:
<Grid>
<Grid.Background>
<local:TiledBrush ImageSourceUri="Assets/Texture.jpg" />
</Grid.Background>
</Grid>