Click here to Skip to main content
14,768,949 members
Articles » Platforms, Frameworks & Libraries » Universal Windows Platform and Windows Runtime » Howto
Tip/Trick
Posted 25 Mar 2018

Tagged as

Stats

5.1K views
147 downloads

UWP TiledBrush

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
25 Mar 2018CPOL
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:

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>

License

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

Share

About the Author

Matej Pavlů
Software Developer
Slovakia Slovakia
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --