1. Composition Lighting
UWP中的Composition Light是一組可以創建3D光照的API,它明明十分好玩而且強大, 但博客園幾乎沒有相關文章(用UWP或pointlight做關鍵字只能找到我自己的文章),這篇文章就 來介紹Composition Lighting的入門知識,
Composition Light有四種型別:
- AmbientLight,發出出現的非定向光源的光源反射場景中的所有內容,
- DistantLight,無限大遠處的光源的發光的一個方向, 如 sun,
- PointLight,發出的所有方向光的光點源, 如燈泡,
- SpotLight,發出的光線的內部和外部圓錐光源, 如手電筒,
這四種型別的它們Composition Light分別使用Compositor的CreateXXXXXLight()函式創建,例如:
var pointLight = compositor.CreatePointLight();

上圖分別是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
Composition Light可以疊加,效果和光學原理一樣,即紅色加藍色會成為紫色,之類之類的,不過要注意的是除了AmbientLight外,其它光照只可以疊加兩個,

這樣就很有可玩性,例如下面這個影片:

4. 結語
上面的影片可以安裝我的番茄鐘應用試玩一下,安裝地址:
一個番茄鐘
Composition Light玩起來真是一發不可收拾,更多示例可以下載Windows Composition Samples 玩玩,
5. 參考
組合照明 - Windows UWP applications Microsoft Docs
XAML 照明 - Windows UWP applications Microsoft Docs
PointLight Class (Windows.UI.Composition) - Windows UWP applications Microsoft Docs
XamlLight Class (Windows.UI.Xaml.Media) - Windows UWP applications Microsoft Docs
6. 原始碼
OnePomodoro_TheBigOne.xaml.cs at master
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/1696.html
標籤:UWP
