Increase Animation Speed Win2d line UWP - c#

I would like to increase the animation speed of the line by keeping the step 1.
Xaml:
<canvas:CanvasAnimatedControl x:Name="canvas"
Margin="0,30,0,0"
Height="500"
Draw="OnDraw"/>
cs:
private bool _adding = true;
private int _Offset = 0;
private void OnDraw(Microsoft.Graphics.Canvas.UI.Xaml.ICanvasAnimatedControl sender, Microsoft.Graphics.Canvas.UI.Xaml.CanvasAnimatedDrawEventArgs args)
{
CanvasDrawingSession ds = args.DrawingSession;
double height = sender.Size.Height;
double width = sender.Size.Width;
var point1 = new Vector2((float)(width / 2), (float)height);
var point2 = new Vector2((float)(width / 2), (float)height - (float)_Offset);
CanvasSolidColorBrush brush = new CanvasSolidColorBrush(sender, Colors.Green);
ds.DrawLine(point1, point2, brush, (float)10);
if (_adding)
{
_Offset++;
}
else
{
_Offset--;
}
if (_Offset == 0 || _Offset == 300)
{
_adding = !_adding;
}
}
Is it possible to keep the _offset step at 1 but increase the line animation speed and to keep TargetElapsedTime at 16?

Related

I need a perspective transformation for a crooked rectangle

Is there some way to rotate an image in a certain way? I will explain it to you: I do not want the rotation in the sense of PictureBox1.Image.RotateFlip(RotateFlipType.Rotate90FlipNone), or as shown here, but rather orient a crooked rectangle to the camera (being flush with the camera).
I made a drawing for this. This is a view from above. Imagine, you are the person who is standing at point (0, 0) and currently taking a picture of the body („Rechteck“). I want to rotate that image by a certain angle, for example 35°, because you stood 35° to the body (perspectively).
I've already prepared some source code and did the math for that.
The code works like follows: The user has to enter the distance from himself to the center of the rectangle, as well as the angle. In the attached picture this is the red line. You also need to know how wide the rectangle is. The program calculates the x and y coordinates (x_v and y_v). The program calculates all distances and angles from the left edge of the rectangle to the right edge.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace schiefes_Rechteck
{
public partial class Form_Main : Form
{
/// <summary>
/// entered angle in degrees
/// </summary>
private Int16 eingegebener_Winkel_in_Grad;
private UInt16 Radius_in_mm;
/// <summary>
/// Length of the rectangle in mm
/// </summary>
private UInt16 Laenge_des_Rechtecks_in_mm;
/// <summary>
/// all distances [mm]
/// </summary>
private List<double> alle_Entfernungen = new List<double>();
/// <summary>
/// all angles [°]
/// </summary>
private List<double> alle_Winkel = new List<double>();
public Form_Main()
{
InitializeComponent();
}
private void Form_Main_Load(object sender, EventArgs e)
{
this.BackColor = Color.FromArgb(148, 148, 109);
this.Location = new Point(0, 0);
Button_Start.BackColor = Color.FromArgb(194, 194, 165);
TextBox_Entfernung.Text = "1300";
TextBox_Winkel.Text = "35";
TextBox_Rechtecklaenge.Text = "503";
if (System.IO.File.Exists(Application.StartupPath + "\\schiefes_Rechteck_Grafik.PNG"))
{
PictureBox1.Image = Image.FromFile(Application.StartupPath + "\\schiefes_Rechteck_Grafik.PNG");
}
}
private void Form_Main_FormClosing(object sender, FormClosingEventArgs e)
{
if (PictureBox1.Image != null)
{
PictureBox1.Image.Dispose();
}
if (PictureBox2.Image != null)
{
PictureBox2.Image.Dispose();
}
}
private void TextBox_Entfernung_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(TextBox_Entfernung.Text))
{
bool erfolgreich = UInt16.TryParse(TextBox_Entfernung.Text, out Radius_in_mm);
if (erfolgreich)
{
TextBox_Entfernung.ForeColor = Color.FromArgb(0, 163, 0);
}
else
{
TextBox_Entfernung.ForeColor = Color.FromArgb(163, 0, 0);
}
}
}
private void TextBox_Winkel_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(TextBox_Winkel.Text))
{
bool erfolgreich = Int16.TryParse(TextBox_Winkel.Text, out eingegebener_Winkel_in_Grad);
if (erfolgreich)
{
TextBox_Winkel.ForeColor = Color.FromArgb(0, 163, 0);
}
else
{
TextBox_Winkel.ForeColor = Color.FromArgb(163, 0, 0);
}
}
}
private void TextBox_Rechtecklaenge_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(TextBox_Rechtecklaenge.Text))
{
bool erfolgreich = UInt16.TryParse(TextBox_Rechtecklaenge.Text, out Laenge_des_Rechtecks_in_mm);
if (erfolgreich)
{
TextBox_Rechtecklaenge.ForeColor = Color.FromArgb(0, 163, 0);
}
else
{
TextBox_Rechtecklaenge.ForeColor = Color.FromArgb(163, 0, 0);
}
}
}
private async void Button_Start_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
await Task.Run(() => Berechnung_aller_Werte());
}
private void Berechnung_aller_Werte()
{
alle_Entfernungen.Clear();
alle_Winkel.Clear();
double x_v, y_v; // Mitte des Rechtecks, davon die x-Koordinate und die y-Koordinate.
x_v = Radius_in_mm * Math.Cos((90.0 - (double)eingegebener_Winkel_in_Grad) * Math.PI / 180.0); //richtig
y_v = Radius_in_mm * Math.Sin((90.0 - (double)eingegebener_Winkel_in_Grad) * Math.PI / 180.0); //richtig
double alpha_in_Grad = 0.0;
double Entfernung = 0.0;
double halbe_Rechteckbreite = Laenge_des_Rechtecks_in_mm / 2.0;
double Position_linker_Rand = x_v - halbe_Rechteckbreite; //richtig
double Zaehler = 0.0;
while (Zaehler < Laenge_des_Rechtecks_in_mm)
{
alpha_in_Grad = Math.Atan((Position_linker_Rand + Zaehler) / y_v) * 180.0 / Math.PI;
alle_Winkel.Add(alpha_in_Grad);
Entfernung = Math.Sqrt(Math.Pow(Position_linker_Rand + Zaehler, 2) + Math.Pow(y_v, 2));
alle_Entfernungen.Add(Entfernung);
Zaehler += 1.0;
}
this.BeginInvoke((Action)(() => { ListBox1.Items.Add(Math.Round(alle_Entfernungen.Last(), 0).ToString() + " mm"); ListBox1.Items.Add(Math.Round(alle_Winkel.Last(), 0).ToString() + " °"); }));
}
}//Form
}
If you want a non-crooked image, i.e., all lines remain either vertical or horizontal, then all what happens to the image is that its width will appear smaller when viewed from the side, and its height will remain the same.
Get the scaling factor for the x-Axis by dividing the apparent angle under which you see the image, i.e., the angle between the yellow-green and the pink lines in your image, by the corresponding angle you would have when standing right in front of the image. A very good approximation for this factor is simply cos(36° * PI / 180), where the angle is the angle to your red line in the image.
xScale = Math.Cos(angleToMidLineInDegrees * Math.PI / 180);
yScale = 1;
or simply
xScale = Math.Cos(angleToMidLineInRadians);
yScale = 1;
where
angleToMidLineInRadians = Math.ATan(x_redLine / y_v);
or in one step
xScale = y_v / Math.Sqrt(x_redLine * x_redLine + y_v * y_v);
See: cos(arctan(x/y)) on WolframAlpha.
However, when transforming an image, you must do the inverse transformation (as explained towards the end of the video), because you want to determine the pixels of the transformed image. I.e., you will do in pseudo code (where t means transformed and without t are the coordinates in the original):
for (yt = 0 to height_t - 1; yt++) {
for (xt = 0 to width_t - 1; xt++) {
(x, y) = inverse_transformation(xt, yt);
color_t = get_color(picture, x, y);
draw(picture_t, xt, yt, color_t);
}
}

how to draw a rectangle on a canvas with mouse, but see the rectangle while moving the mouse

i'm new to WPF, learning by migrating an existing winforms app.
i'm drawing rectangles on a Canvas, which contains an Image. the rectangles get the X,Y, and Z information from the imported IntPtr object on the Image, which is then analysed as data.
drawing the rectangles is easy enough with Children.Add() and the data capture is working fine, but i can only see the rectangle once it's drawn, so it's hard to know what area you are going to select. i'd like to see it during the drawing as the mouse moves (like a standard lasso rectangle). in winforms i used the Paint event, how to do similar in WPF? i'm using MouseDown and MouseUp events to capture the start and end points of the rectangle
public void MouseDown(MouseButtonEventArgs e, Canvas evImage)
{
if (e.LeftButton == MouseButtonState.Pressed)
startPos = e.GetPosition(evImage);
evImage.CaptureMouse();
}
public void MouseUp(MouseButtonEventArgs e, Canvas evImage)
{
if (Constants.count < 3)
{
if (e.LeftButton == MouseButtonState.Released)
currentPos = e.GetPosition(evImage);
rec = new System.Windows.Shapes.Rectangle()
{
Stroke = System.Windows.Media.Brushes.LightBlue,
StrokeThickness = 1,
Name = "rec" + Constants.count.ToString(),
};
if (startPos.X < currentPos.X)
rec.Width = currentPos.X - startPos.X;
else
rec.Width = startPos.X - currentPos.X;
if (startPos.Y < currentPos.Y)
rec.Height = currentPos.Y - startPos.Y;
else
rec.Height = startPos.Y - currentPos.Y;
if (rec.Height < 8)
rec.Height = 8;
if (rec.Width < 8)
rec.Width = 8;
if (evImage.Children.Count > Constants.count + 1)
evImage.Children.RemoveAt(Constants.count + 1);
evImage.Children.Insert(Constants.count + 1, rec);
Canvas.SetLeft(rec, startPos.X);
Canvas.SetTop(rec, startPos.Y);
evImage.ReleaseMouseCapture();
SetRectangleData();
Constants.count++;
}
else
{
Constants.count = 0;
RecMove(e, evImage);
}
}
XAML - this is my main learning point, i don't know if using the Image in the Canvas is a problem, or if i need to reference something here like the rectangle?
<Canvas x:Name="evCanvas" MouseUp="evCanvas_MouseUp" MouseDown="evCanvas_MouseDown" Grid.Column="1" Height="550" Width="626" HorizontalAlignment="Left" Margin="10,43,0,0" Grid.Row="1" VerticalAlignment="Top" Grid.ColumnSpan="2" Grid.RowSpan="2">
<Image x:Name="evImage" Height="550" Width="626" MouseMove="evImage_MouseMove" RenderTransformOrigin=".5,.5" />
</Canvas>
Just set Left and Top to the minimum x and y and width to max-x and height max-y.
<Canvas x:Name="canvas" MouseDown="Canvas_MouseDown" MouseMove="Canvas_MouseMove" MouseUp="Canvas_MouseUp" Background="Transparent" />
Then doing as follows:
private Point startPoint;
private Rectangle rect;
private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
startPoint = e.GetPosition(canvas);
rect = new Rectangle
{
Stroke = Brushes.LightBlue,
StrokeThickness = 2
};
Canvas.SetLeft(rect,startPoint.X);
Canvas.SetTop(rect,startPoint.Y);
canvas.Children.Add(rect);
}
private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
if(e.LeftButton == MouseButtonState.Released || rect == null)
return;
var pos = e.GetPosition(canvas);
var x = Math.Min(pos.X, startPoint.X);
var y = Math.Min(pos.Y, startPoint.Y);
var w = Math.Max(pos.X, startPoint.X) - x;
var h = Math.Max(pos.Y, startPoint.Y) - y;
rect.Width = w;
rect.Height = h;
Canvas.SetLeft(rect, x);
Canvas.SetTop(rect, y);
}
private void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
rect = null;
}

Zoom-able CarouselView in Xamarin.form

I'm using carousel view to display a number of images, changeable upon sliding. The problem I'm having is that these images are not zoom-able. Is there any way to enable zooming within carousel view? Thanks.
Ok so the First Thing first Carousel View is not a gud thing which you want to make zoom (for Practical Case)
and as client demands out of the Galaxy things so you can make things work out with some logic
1st Way:
Create a Class Name ZoomImage in Your Shared Xamarin.forms Solution and Add this code in it
public class ZoomImage : Image {
private const double MIN_SCALE = 1;
private const double MAX_SCALE = 4;
private const double OVERSHOOT = 0.15;
private double StartScale;
private double LastX, LastY;
public ZoomImage() {
var pinch = new PinchGestureRecognizer();
pinch.PinchUpdated += OnPinchUpdated;
GestureRecognizers.Add(pinch);
var pan = new PanGestureRecognizer();
pan.PanUpdated += OnPanUpdated;
GestureRecognizers.Add(pan);
var tap = new TapGestureRecognizer { NumberOfTapsRequired = 2 };
tap.Tapped += OnTapped;
GestureRecognizers.Add(tap);
Scale = MIN_SCALE;
TranslationX = TranslationY = 0;
AnchorX = AnchorY = 0;
}
protected override SizeRequest OnMeasure(double widthConstraint, double heightConstraint) {
Scale = MIN_SCALE;
TranslationX = TranslationY = 0;
AnchorX = AnchorY = 0;
return base.OnMeasure(widthConstraint, heightConstraint);
}
private void OnTapped(object sender, EventArgs e) {
if (Scale > MIN_SCALE) {
this.ScaleTo(MIN_SCALE, 250, Easing.CubicInOut);
this.TranslateTo(0, 0, 250, Easing.CubicInOut);
}
else {
AnchorX = AnchorY = 0.5; //TODO tapped position
this.ScaleTo(MAX_SCALE, 250, Easing.CubicInOut);
}
}
private void OnPanUpdated(object sender, PanUpdatedEventArgs e) {
if (Scale > MIN_SCALE)
switch (e.StatusType) {
case GestureStatus.Started:
LastX = TranslationX;
LastY = TranslationY;
break;
case GestureStatus.Running:
TranslationX = Clamp(LastX + e.TotalX * Scale, -Width / 2, Width / 2);
TranslationY = Clamp(LastY + e.TotalY * Scale, -Height / 2, Height / 2);
break;
}
}
private void OnPinchUpdated(object sender, PinchGestureUpdatedEventArgs e) {
switch (e.Status) {
case GestureStatus.Started:
StartScale = Scale;
AnchorX = e.ScaleOrigin.X;
AnchorY = e.ScaleOrigin.Y;
break;
case GestureStatus.Running:
double current = Scale + (e.Scale - 1) * StartScale;
Scale = Clamp(current, MIN_SCALE * (1 - OVERSHOOT), MAX_SCALE * (1 + OVERSHOOT));
break;
case GestureStatus.Completed:
if (Scale > MAX_SCALE)
this.ScaleTo(MAX_SCALE, 250, Easing.SpringOut);
else if (Scale < MIN_SCALE)
this.ScaleTo(MIN_SCALE, 250, Easing.SpringOut);
break;
}
}
private T Clamp<T>(T value, T minimum, T maximum) where T : IComparable {
if (value.CompareTo(minimum) < 0)
return minimum;
else if (value.CompareTo(maximum) > 0)
return maximum;
else
return value;
}
}
and now In Xaml within carousel view Use Image Like This
<cv:CarouselView x:Name="itemPictureGallery" Grid.Column="0" Grid.Row="0">
<cv:CarouselView.ItemTemplate>
<DataTemplate>
<local:image source="YOUR_PIC_SOURCE" />
</DataTemplate>
</cv:CarouselView.ItemTemplate>
</cv:CarouselView>
Dont Forget to add nameSpace in Xamal
xmlns:local="clr-namespace:YOUR_APP_NAME"
so this is how the image can zoom etiher
Or Second Way is
add an Item Tapped on carousel view and pass the picture source in command parameter and open a new page with that picture in it and apply zoom with in it
i use that logic for figure out my problem
Hope this Helps :)
This can be achieved by using
alexrainman/CarouselView for the carousal view.
https://github.com/alexrainman/CarouselView
and add Xamarin forms pinch gesture recognizer according to the forms sample to the image used in carousal view
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/gestures/pinch

How merge 3 joints and overlay a image onto it so that image rotates

I have created a Kinect app using WPF and Microsoft Kinect SDK v2.
I have successfully displayed an image on all joint points using the following code:
// Draw
if (joint.JointType == JointType.SpineShoulder)
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(#"C:\Users\myimage.jpg", UriKind.Relative);
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
var img = new Image { Source = bitmap, Height = 50, Width = 50 };
Canvas.SetLeft(img, point.X - img.Width / 2);
Canvas.SetTop(img, point.Y - img.Height / 2);
canvas.Children.Add(img);}
Now instead of an image on each joint, I want to merge 3 joints (spine_shoulder - center joint , shoulder right , shoulder left) its my opinion and overlay an image onto them, so that image rotates according to how joint positions change.
I tried using the code explained in this article, with no luck...
lets assume if we overlay the image on top of any block how it show
how it will rotate https://www.youtube.com/watch?v=pAljofdcMw8
As suggested by #Vangos I tried like below
public partial class Window1 : Window
{
public static ObservableCollection<string> selectedImg = new ObservableCollection<string>();
KinectSensor _sensor;
MultiSourceFrameReader _reader;
IList<Body> _bodies;
private static string imagepath = #"C:\Users\demo.png";
CameraMode _mode = CameraMode.Color;
public Window1()
{
InitializeComponent();
imageItems.ItemsSource = Page1.folders;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
_sensor = KinectSensor.GetDefault();
if (_sensor != null)
{
_sensor.Open();
_reader = _sensor.OpenMultiSourceFrameReader(FrameSourceTypes.Color | FrameSourceTypes.Depth | FrameSourceTypes.Infrared | FrameSourceTypes.Body);
_reader.MultiSourceFrameArrived += Reader_MultiSourceFrameArrived;
}
}
void Reader_MultiSourceFrameArrived(object sender, MultiSourceFrameArrivedEventArgs e)
{
var reference = e.FrameReference.AcquireFrame();
// Body
using (var frame = reference.BodyFrameReference.AcquireFrame())
{
if (frame != null)
{
canvas.Children.Clear();
_bodies = new Body[frame.BodyFrameSource.BodyCount];
frame.GetAndRefreshBodyData(_bodies);
foreach (var body in _bodies)
{
if (body.IsTracked)
{
// COORDINATE MAPPING
foreach (Joint joint in body.Joints.Values)
{
if (joint.TrackingState == TrackingState.Tracked)
{
// 3D space point
CameraSpacePoint jointPosition = joint.Position;
// 2D space point
Point point = new Point();
if (_mode == CameraMode.Color)
{
ColorSpacePoint colorPoint = _sensor.CoordinateMapper.MapCameraPointToColorSpace(jointPosition);
point.X = float.IsInfinity(colorPoint.X) ? 0 : colorPoint.X;
point.Y = float.IsInfinity(colorPoint.Y) ? 0 : colorPoint.Y;
}
else if (_mode == CameraMode.Depth || _mode == CameraMode.Infrared) // Change the Image and Canvas dimensions to 512x424
{
DepthSpacePoint depthPoint = _sensor.CoordinateMapper.MapCameraPointToDepthSpace(jointPosition.);
point.X = float.IsInfinity(depthPoint.X) ? 0 : depthPoint.X;
point.Y = float.IsInfinity(depthPoint.Y) ? 0 : depthPoint.Y;
}
//// Draw a images based on joint type
JointType _start = JointType.SpineShoulder;
JointType _center = JointType.ShoulderRight;
JointType _end = JointType.ShoulderLeft;
if (joint.JointType == JointType.SpineShoulder)
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(imagepath, UriKind.Relative);
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
var img = new Image { Source = bitmap, Height = 50, Width = 50 };
//Add a RotateTransform
img.RenderTransformOrigin = new Point(0.5, 0.5);
double angle = Extension.Angle(body.Joints[_start], body.Joints[_center], body.Joints[_end]);
img.RenderTransform = new RotateTransform(angle);
Canvas.SetLeft(img, point.X - img.Width / 2);
Canvas.SetTop(img, point.Y - img.Height / 2);
canvas.Children.Add(img);
}
}
}
}
}
}
}
}
}
enum CameraMode
{
Color,
Depth,
Infrared
}
You can use the following algorithm:
1) Find the angle between the joints (code).
using LightBuzz.Vitruvius;
double angle = joint1.Angle(joint2, joint3);
2) Add a RotateTransform to the desired image and rotate the image according to the angle you calculated.
img.RenderTransformOrigin = new Point(0.5, 0.5);
img.RenderTransform = new RotateTransform(angle);
Your XAML code:
<Grid>
<Canvas Name="canvas" Width="1920" Height="1080">
<Image Name="img" Width="50" Height="50" />
</Canvas>
</Grid>
Your Event Handler:
void Reader_MultiSourceFrameArrived(object sender, MultiSourceFrameArrivedEventArgs e)
{
var reference = e.FrameReference.AcquireFrame();
using (var frame = reference.BodyFrameReference.AcquireFrame())
{
if (frame != null)
{
var body = frame.Bodies().Closest();
if (body != null)
{
JointType _start = JointType.SpineShoulder;
JointType _center = JointType.ShoulderRight;
JointType _end = JointType.ShoulderLeft;
double angle = body.Joints[_center].Angle(body.Joints[_start], body.Joints[_end]);
Point point = new Point();
ColorSpacePoint colorPoint = _sensor.CoordinateMapper.MapCameraPointToColorSpace(body.Joints[_center].Position);
point.X = float.IsInfinity(colorPoint.X) ? 0 : colorPoint.X;
point.Y = float.IsInfinity(colorPoint.Y) ? 0 : colorPoint.Y;
img.Source = new BitmapImage(new Uri("your-image-path", UriKind.RelativeOrAbsolute));
img.RenderTransformOrigin = new Point(0.5, 0.5);
img.RenderTransform = new RotateTransform(angle);
Canvas.SetLeft(img, point.X - img.Width / 2);
Canvas.SetTop(img, point.Y - img.Height / 2);
}
}
}
}

How to move an image from one point to another point in an canvas

I am writing a program in that i want to move an image from one position to another position when the pointer is on the image.the destination of an image will be anywhere in the window.
And,while moving to the destination the image size has to gradually decrease to some particular size.
I am using WPF C# for this
Thanks in advance
See the Channel 9 Kinect QuickStart Series(Skeletal Tracking Fundementals) For moving the images, and I will add code. For the changing image size I would use something like Flying Text in Shape Game. Hope this Helps!Moving the Image(XAML)
<Window x:Class="SkeletalTracking.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="600" Width="800" Loaded="Window_Loaded"
xmlns:my="clr-namespace:Microsoft.Samples.Kinect.WpfViewers;assembly=Microsoft.Samples.Kinect.WpfViewers"
Closing="Window_Closing" WindowState="Maximized">
<Canvas Name="MainCanvas">
<my:KinectColorViewer Canvas.Left="0" Canvas.Top="0" Width="640" Height="480" Name="kinectColorViewer1"
Kinect="{Binding ElementName=kinectSensorChooser1, Path=Kinect}" />
<my:KinectSensorChooser Canvas.Left="250" Canvas.Top="380" Name="kinectSensorChooser1" Width="328" />
<Image Canvas.Left="66" Canvas.Top="90" Height="87" Name="headImage" Stretch="Fill" Width="84" Source="/SkeletalTracking;component/c4f-color.png" />
</Canvas>
Inner Code
void sensor_AllFramesReady(object sender, AllFramesReadyEventArgs e)
{
if (closing)
{
return;
}
//Get a skeleton
Skeleton first = GetFirstSkeleton(e);
if (first == null)
{
return;
}
//set scaled position
//ScalePosition(headImage, first.Joints[JointType.Head]);
GetCameraPoint(first, e);
}
void GetCameraPoint(Skeleton first, AllFramesReadyEventArgs e)
{
using (DepthImageFrame depth = e.OpenDepthImageFrame())
{
if (depth == null ||
kinectSensorChooser1.Kinect == null)
{
return;
}
//Map a joint location to a point on the depth map
//head
DepthImagePoint headDepthPoint =
depth.MapFromSkeletonPoint(first.Joints[JointType.Head].Position);
//Map a depth point to a point on the color image
//head
ColorImagePoint headColorPoint =
depth.MapToColorImagePoint(headDepthPoint.X, headDepthPoint.Y,
ColorImageFormat.RgbResolution640x480Fps30);
}
Skeleton GetFirstSkeleton(AllFramesReadyEventArgs e)
{
using (SkeletonFrame skeletonFrameData = e.OpenSkeletonFrame())
{
if (skeletonFrameData == null)
{
return null;
}
skeletonFrameData.CopySkeletonDataTo(allSkeletons);
//get the first tracked skeleton
Skeleton first = (from s in allSkeletons
where s.TrackingState == SkeletonTrackingState.Tracked
select s).FirstOrDefault();
return first;
}
}
private void ScalePosition(FrameworkElement element, Joint joint)
{
//convert the value to X/Y
//Joint scaledJoint = joint.ScaleTo(1280, 720);
//convert & scale (.3 = means 1/3 of joint distance)
Joint scaledJoint = joint.ScaleTo(1280, 720, .3f, .3f);
Canvas.SetLeft(element, scaledJoint.Position.X);
Canvas.SetTop(element, scaledJoint.Position.Y);
}
Flying Text(class)
public class FlyingText
{
private static readonly List<FlyingText> FlyingTexts = new List<FlyingText>();
private readonly double fontGrow;
private readonly string text;
private System.Windows.Point center;
private System.Windows.Media.Brush brush;
private double fontSize;
private double alpha;
private Label label;
public FlyingText(string s, double size, System.Windows.Point center)
{
this.text = s;
this.fontSize = Math.Max(1, size);
this.fontGrow = Math.Sqrt(size) * 0.4;
this.center = center;
this.alpha = 1.0;
this.label = null;
this.brush = null;
}
public static void NewFlyingText(double size, System.Windows.Point center, string s)
{
FlyingTexts.Add(new FlyingText(s, size, center));
}
public static void Draw(UIElementCollection children)
{
for (int i = 0; i < FlyingTexts.Count; i++)
{
FlyingText flyout = FlyingTexts[i];
if (flyout.alpha <= 0)
{
FlyingTexts.Remove(flyout);
i--;
}
}
foreach (var flyout in FlyingTexts)
{
flyout.Advance();
children.Add(flyout.label);
}
}
private void Advance()
{
this.alpha -= 0.01;
if (this.alpha < 0)
{
this.alpha = 0;
}
if (this.brush == null)
{
this.brush = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 255, 255, 255));
}
if (this.label == null)
{
return;
}
this.brush.Opacity = Math.Pow(this.alpha, 1.5);
this.label.Foreground = this.brush;
this.fontSize += this.fontGrow;
this.label.FontSize = Math.Max(1, this.fontSize);
Rect renderRect = new Rect(this.label.RenderSize);
this.label.SetValue(Canvas.LeftProperty, this.center.X - (renderRect.Width / 2));
this.label.SetValue(Canvas.TopProperty, this.center.Y - (renderRect.Height / 2));
}
}
The Code In Your Project
FlyingText.FlyingText.NewFlyingText(this.skeleton.Width / 30, new Point(this.skeleton.Width / 2,
this.skeleton.Height / 2), e.Matched);
Now obviously you want your image to be smaller, and not text, but I figure you can work that out on your own, also your would change the images in XAML to whatever you wanted and the Joints to whatever joints you wanted too.

Categories

Resources