#738 – Sample Code – Drawing and Moving Circles at Touch Points
January 21, 2013 1 Comment
Here’s some sample code that draws a circle for each touch point, when a finger contacts the screen, and then moves that circle around as you move your finger. This is done using the raw touch events–TouchDown, TouchMove and TouchUp.
<Canvas Name="canvMain" Background="Transparent"
TouchDown="Canvas_TouchDown" TouchUp="Canvas_TouchUp" TouchMove="Canvas_TouchMove"/>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
TouchPositions = new Dictionary<int, Point>();
TouchEllipses = new Dictionary<int, Ellipse>();
}
private const double CircleWidth = 55;
private Dictionary<int, Point> TouchPositions;
private Dictionary<int, Ellipse> TouchEllipses;
private void Canvas_TouchDown(object sender, TouchEventArgs e)
{
canvMain.CaptureTouch(e.TouchDevice);
TouchPoint tp = e.GetTouchPoint(null);
Ellipse el = AddEllipseAt(canvMain, tp.Position, Brushes.Red);
TouchPositions.Add(e.TouchDevice.Id, tp.Position);
TouchEllipses.Add(e.TouchDevice.Id, el);
e.Handled = true;
}
private void Canvas_TouchMove(object sender, TouchEventArgs e)
{
TouchPoint tp = e.GetTouchPoint(null);
Canvas.SetLeft(TouchEllipses[e.TouchDevice.Id], tp.Position.X - (CircleWidth / 2));
Canvas.SetTop(TouchEllipses[e.TouchDevice.Id], tp.Position.Y - (CircleWidth / 2));
e.Handled = true;
}
private void Canvas_TouchUp(object sender, TouchEventArgs e)
{
TouchPoint tp = e.GetTouchPoint(null);
TouchPositions.Remove(e.TouchDevice.Id);
canvMain.Children.Remove(TouchEllipses[e.TouchDevice.Id]);
TouchEllipses.Remove(e.TouchDevice.Id);
canvMain.ReleaseTouchCapture(e.TouchDevice);
e.Handled = true;
}
private Ellipse AddEllipseAt(Canvas canv, Point pt, Brush brush)
{
Ellipse el = new Ellipse();
el.Stroke = brush;
el.Fill = brush;
el.Width = CircleWidth;
el.Height = CircleWidth;
Canvas.SetLeft(el, pt.X - (CircleWidth / 2));
Canvas.SetTop(el, pt.Y - (CircleWidth / 2));
canv.Children.Add(el);
return el;
}
}

Pingback: Dew Drop – January 21, 2013 (#1,483) | Alvin Ashcraft's Morning Dew