はつねの日記

Kinect, Windows 10 UWP, Windows Azure, IoT, 電子工作

KinectというかWPFの基礎

赤い点を点滅させるXAML定義
    <Window.Resources>
<RadialGradientBrush x:Key="em_Brush">
<GradientStop Color="#00FFFFFF" Offset="1" />
<GradientStop Color="#D6FF0000" Offset="0.4" />
<GradientStop Color="#FFFF0000" Offset="0" />
</RadialGradientBrush>
<Style TargetType="Ellipse" x:Key="em">
<Setter Property="Stroke" Value="#00FFFFFF" />
<Setter Property="Fill" Value="{StaticResource em_Brush}" />
<Setter Property="Height" Value="10"/>
<Setter Property="Width" Value="10"/>
<Style.Triggers>
<EventTrigger RoutedEvent="Ellipse.Loaded">
<BeginStoryboard>
<Storyboard RepeatBehavior="Forever" >
<DoubleAnimation Name="a" Storyboard.TargetProperty="Opacity"
From="0" To="1" Duration="0:0:0.3" AutoReverse="false" />
<DoubleAnimation Storyboard.TargetProperty="Opacity"
From="1" To="0" Duration="0:0:0.1" AutoReverse="false"
BeginTime="00:00:0.3" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Style.Triggers>
</Style>
</Window.Resources>

<Grid>
<Canvas Name="Base_Canvas">
</Canvas>
</Grid>


Window.ResourcesでRadialGradientBrushとStyleを指定しています。


RadialGradientBrushは中心が赤で0.4のところまで透明度があがり、そこから白透明に変化するようなBrushです。


StyleではElipseに対するスタイルとStoryboardを定義しています。


Storyboardには0.3秒で点灯し、その直後に0.1秒で消灯する無限繰り返しのアニメーションを設定しています。


このようにStyleを定義しておけば同じ動作をする点を描画する時にStyleのKey名である”em”を指定するだけで済みます。


赤い点を移動させるプログラムコード

XAML側の定義が終わったので点を生成してタイマーイベントで動かすコードを書いてみましょう。

Class MainWindow

Private Dot As New List(Of Ellipse)
Private DotCount As Integer
Private WithEvents Timer As New Windows.Threading.DispatcherTimer()
Private r As New Random(DateTime.Now.Millisecond)

Private Sub MainWindow_Loaded(sender As Object,
e As System.Windows.RoutedEventArgs) Handles Me.Loaded
Me.WindowState = Windows.WindowState.Maximized
DotCount = Math.Ceiling(Me.Height / 40)
For index = 0 To DotCount - 1
Dot.Add(New Ellipse With {.Style = Me.Resources("em")})
Me.Base_Canvas.Children.Add(Dot(index))
Canvas.SetLeft(Dot(index), 0)
Canvas.SetTop(Dot(index), index * 40 + 20)
Next
Me.Timer.Interval = TimeSpan.FromMilliseconds(40)
Me.Timer.Start()
End Sub

Private Sub Timer_Tick(sender As Object, e As System.EventArgs) Handles Timer.Tick
Me.Timer.Stop()
For index = 0 To DotCount - 1
Dim posX As Double = Canvas.GetLeft(Dot(index)) + 10
Dim posY As Double = Canvas.GetTop(Dot(index))
If posX > Me.Width Then
posX = 0
End If
'ここにYの処理
'
Canvas.SetLeft(Dot(index), posX)
Canvas.SetTop(Dot(index), posY)
Next
Me.Timer.Start()
End Sub
End Class


画面の縦方向に40ドットごとに点を配置し、40msごとに10ドットづつ右に移動するようにした例になります。


「New Ellipse With {.Style = Me.Resources("em")}」でEllipseを生成しているのでXAMLに定義したStyleが割り当てられ点滅動作はコードではまったく記述せずXAML側のアニメーションにゆだねる事ができます。