Click here to Skip to main content
15,868,016 members
Articles / Desktop Programming / Universal Windows Platform
Tip/Trick

UWP TiledBrush

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
25 Mar 2018CPOL1 min read 7.1K   178  
Creating a replacement for missing TileBrush known from WPF

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:

C#
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:

XML
<Grid>
    <Grid.Background>
        <local:TiledBrush ImageSourceUri="Assets/Texture.jpg" />
    </Grid.Background>
</Grid>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Slovakia Slovakia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --