Skip to content

Instantly share code, notes, and snippets.

@jesbis
Created April 8, 2019 22:17
Show Gist options
  • Save jesbis/774eb0294132a7137957cb9b39b44717 to your computer and use it in GitHub Desktop.
Save jesbis/774eb0294132a7137957cb9b39b44717 to your computer and use it in GitHub Desktop.
UWP Xaml tiling image brush
public sealed class ImageTileBrush : XamlCompositionBrushBase
{
private CompositionSurfaceBrush _surfaceBrush;
public ImageTileBrush() { }
public static readonly DependencyProperty ImageSourceUriProperty = DependencyProperty.Register(
"ImageSourceUri",
typeof(Uri),
typeof(ImageTileBrush),
new PropertyMetadata(null, OnImageSourceUriChanged)
);
public Uri ImageSourceUri
{
get { return (Uri)GetValue(ImageSourceUriProperty); }
set { SetValue(ImageSourceUriProperty, value); }
}
private static void OnImageSourceUriChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var brush = (ImageTileBrush)o;
if (brush.CompositionBrush != null)
{
var surface = LoadedImageSurface.StartLoadFromUri(new Uri(e.NewValue.ToString()));
brush._surfaceBrush.Surface = surface;
}
}
protected override void OnConnected()
{
// Delay creating composition resources until they're required.
if (CompositionBrush == null)
{
var surface = LoadedImageSurface.StartLoadFromUri(ImageSourceUri);
_surfaceBrush = Window.Current.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 = Window.Current.Compositor.CreateEffectFactory(borderEffect);
var borderEffectBrush = borderEffectFactory.CreateBrush();
borderEffectBrush.SetSourceParameter("source", _surfaceBrush);
CompositionBrush = borderEffectBrush;
}
}
protected override void OnDisconnected()
{
// Dispose of composition resources when no longer in use.
if (CompositionBrush != null)
{
CompositionBrush.Dispose();
CompositionBrush = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment