[UWP]使用PointLight并实现动画效果
1. Composition Lighting
上图分别是SpotLight和PointLight的效果(其它两个截图没什么好看的)。
2. 使用PointLight#
使用PointLight最基础的例子是WindowsCompositionSamples中的 TextShimmer 例子,下面用这个例子的代码介绍如何使用PointLight。
首先把需要应用PointLight的的TextBlock添加到UI,颜色为DimGray。
<TextBlock Name="TextBlock" FontSize="100" Foreground="DimGray" FontFamily="SegoeUI" FontWeight="Thin" TextAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Center"> Text Shimmer </TextBlock>
然后获取这个TextBlock的Visual对象,用Compositor.CreatePointLight()
创建PointLight,并且设置CoordinateSpace
和Targets
,这两个属性用于关联Visual对象和PointLight。这时候TextBlock变成全黑,除非PointLight应用到它的位置。
_compositor = ElementCompositionPreview.GetElementVisual(TextBlock).Compositor; //get interop visual for XAML TextBlock var text = ElementCompositionPreview.GetElementVisual(TextBlock); _pointLight = _compositor.CreatePointLight(); _pointLight.Color = Colors.White; _pointLight.CoordinateSpace = text; //set up co-ordinate space for offset _pointLight.Targets.Add(text); //target XAML TextBlock
PointLight的主要属性包含Color和Offset,Color默认是白色,而下面这段代码实现Offset的动画。
Offset是一个Vector3
的属性,X、Y和Z代表PointLight的光源在三维空间的坐标。首先将PointLight的Offset设置为TextBlock的左边,垂直居中,Z为TextBlock的FontSize。然后启动一个一直重复的动画,以TextBlock的右边为目标水平移动。
//starts out to the left; vertically centered; light's z-offset is related to fontsize _pointLight.Offset = new Vector3(-(float)TextBlock.ActualWidth, (float)TextBlock.ActualHeight / 2, (float)TextBlock.FontSize); //simple offset.X animation that runs forever var animation = _compositor.CreateScalarKeyFrameAnimation(); animation.InsertKeyFrame(1, 2 * (float)TextBlock.ActualWidth); animation.Duration = TimeSpan.FromSeconds(3.3f); animation.IterationBehavior = AnimationIterationBehavior.Forever; _pointLight.StartAnimation("Offset.X", animation);
运行效果如下:
3. 叠加Composition Light
这样就很有可玩性,例如下面这个动画:
4. 结语#
上面的动画可以安装我的番茄钟应用试玩一下,安装地址: