using System;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace Smoke
{
public class SmokeImage : Canvas
{
private Random _rnd = new Random();
private Image _smoke;
// Control the speed of the smoke going up
private double _velocityX;
private double _velocityY;
// dissipates rate of somke as it rises
private double _currentScale;
// X and Y is used to position starting location of the smoke
public double X
{
get { return (double)(GetValue(Canvas.LeftProperty)); }
set { SetValue(Canvas.LeftProperty, value); }
}
public double Y
{
get { return (double)(GetValue(Canvas.TopProperty)); }
set { SetValue(Canvas.TopProperty, value); }
}
public SmokeImage()
{
// Set speed of smoke rising random so it is more realistic
_velocityX = _rnd.Next(-1, 1) - _rnd.Next(-1, 1);
_velocityY = _rnd.Next(-1, 1) * 3 - 5;
_smoke = new Image();
_smoke.Width = 40;
_smoke.Height = 40;
_smoke.Source = new BitmapImage(new Uri("/Smoke;component/smoke.png", UriKind.Relative));
this.Children.Add(_smoke);
// create different smokes dark to faded
_smoke.Opacity = _rnd.Next(0, 100);
// create different size of smoke
_currentScale = _rnd.Next(1);
ScaleTransform scale = new ScaleTransform();
scale.ScaleX = _currentScale;
scale.ScaleY = _currentScale;
_smoke.RenderTransform = scale;
// set frame rate higher the frame rate more smokes it will create
App.Current.Host.Settings.MaxFrameRate = 12;
CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
}
void CompositionTarget_Rendering(object sender, EventArgs e)
{
// Smoke fades as it rises
_smoke.Opacity -= 1;
// Smoke rises up
Canvas.SetLeft(_smoke, Canvas.GetLeft(_smoke)+_velocityX);
Canvas.SetTop(_smoke, Canvas.GetTop(_smoke)+_velocityY);
// Smoke dissipates
_currentScale += 0.09;
ScaleTransform scale = new ScaleTransform();
scale.ScaleX = _currentScale;
scale.ScaleY = _currentScale;
_smoke.RenderTransform = scale;
// remove smoke if it fades completely
if (_smoke.Opacity < 0)
{
RemoveSelf();
}
}
private void RemoveSelf()
{
CompositionTarget.Rendering -= new EventHandler(CompositionTarget_Rendering);
((Canvas)this.Parent).Children.Remove(this);
}
}
}