Example; sweeping light source in UWP

What it looks like, in Kanban Ink

I was asked on Twitter how I got this effect, here is the code I use.

In this example, the target FrameworkElement is a TextBlock.

Note: I feel really bad as I cannot take credit for writing this, but I cannot remember for the life of me where I found it! If you know, please let me know so I can credit properly.

private void StartShimmerOnLoadingControl()
{
             //get interop compositor
             _compositor = elementCompositionPreview.GetElementVisual(tbLoadingText).Compositor;//get interop visual for XAML TextBlock
        var text = ElementCompositionPreview.GetElementVisual(tbLoadingText);

        _pointLight = _compositor.CreatePointLight();
        _pointLight.Color = Colors.LightGray;
        _pointLight.CoordinateSpace = text; //set up co-ordinate space for offset
        _pointLight.Targets.Add(text); //target XAML TextBlock

        //starts out to the left; vertically centered; light's z-offset is related to fontsize
        _pointLight.Offset = new Vector3(-(float)tbLoadingText.ActualWidth, (float)tbLoadingText.ActualHeight / 2, (float)tbLoadingText.FontSize);

        //simple offset.X animation that runs forever
        var animation = _compositor.CreateScalarKeyFrameAnimation();
        animation.InsertKeyFrame(1, 2 * (float)tbLoadingText.MinWidth);
        animation.Duration = TimeSpan.FromSeconds(3f);
        animation.IterationBehavior = AnimationIterationBehavior.Forever;

        _pointLight.StartAnimation("Offset.X", animation);
    }

    private Compositor _compositor;
    private PointLight _pointLight;

Edit: I remembered the source! It is in the Windows Composition Samples

Leave a Reply

Your email address will not be published. Required fields are marked *