[VS2010 Online]Silverlight 4 哈哈鏡
最近在辦公室內,有一些同仁玩起了「哈哈鏡」,實在是很有趣味,如下圖:
這些實在是很爆笑,讓我想到可以利用 Silverlight 4.0 的新功能 – webcam 來玩看看。
寫法真的很簡單,就是放置兩個 Rectangle,然後其中一個是另一個的映射:
1:
2: <Grid x:Name="LayoutRoot" Background="White">
3: <Canvas x:Name="uxCanvas">
4: <Rectangle x:Name="uxRect" Width="162" Height="175" Canvas.Left="28" Canvas.Top="97" RenderTransformOrigin="0.5,0.5" UseLayoutRounding="False" d:LayoutRounding="Auto" >
5: </Rectangle>
6: <Rectangle x:Name="uxRect2" Width="162" Height="175" Canvas.Left="187" Canvas.Top="97" RenderTransformOrigin="0.5,0.5" UseLayoutRounding="False" d:LayoutRounding="Auto" >
7:
8: </Rectangle>
9: </Canvas>
10: <Button Content="啟動視訊" Height="23" HorizontalAlignment="Left" Margin="17,12,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
11: </Grid>
當按下啟動視訊時,去觸發 Webcam,然後把影像設定為 Rectangle 的內容。
1: private void button1_Click(object sender, RoutedEventArgs e)
2: {
3: VideoCaptureDevice videoCap =
4: CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
5: AudioCaptureDevice audioCap =
6: CaptureDeviceConfiguration.GetDefaultAudioCaptureDevice();
7: CaptureSource capsource = new CaptureSource();
8: capsource.AudioCaptureDevice = audioCap;
9: capsource.VideoCaptureDevice = videoCap;
10: if (CaptureDeviceConfiguration.AllowedDeviceAccess
11: || CaptureDeviceConfiguration.RequestDeviceAccess())
12: {
13: capsource.Start();
14: VideoBrush vidBrush = new VideoBrush();
15: vidBrush.SetSource(capsource);
16:
17:
18: ScaleTransform s = new ScaleTransform();
19: s.ScaleX = -1;
20: s.ScaleY = 1;
21: uxRect2.RenderTransform = s;
22:
23:
24: uxRect.Fill = vidBrush;
25: uxRect2.Fill = vidBrush;
26: }
27:
28:
29: }
這邊要注意到用了一個 ScaleTransform 去作映射的處理,然後把這個 VideoBrush 設定給第二個 Rectangle
作為筆刷來源。
然後按下啟動視訊,這就是結果:
魯夫跟喬巴也說它們要入鏡:
這樣的功能是不是很好玩? 快來玩 Silverlight 4吧。
試煉大會,我們下次見囉~
如果您有微軟技術開發的問題,可以到MSDN Forum發問。
如果您有微軟IT管理的問題,可以到TechNet Forum發問喔。