My first Windows Phone 7 Experiment

OK, It doesn’t look like much. It’s not. I was experimenting with some CompositionTarget Rendering and WriteableBitmap stuff on the plane ride out to Mix 2010 on Sunday and created a little animating blue line thing. (I don’t know what to to call it). But it was a work in progress.

I took the code and copied it into a Windows Phone 7 Silverlight application and hit run. It worked right out of the box. (Using the CTP download from here).

image

CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);

The event:

void CompositionTarget_Rendering(object sender, EventArgs e)
{
    int indx = _shapes.Count - 1;
    double littleCircleHeight = littleCircle.ActualHeight;

    while (indx >= 0)
    {
        Sparkle sparkle = _shapes[indx];
        sparkle.Y += sparkle.VY;
        sparkle.X += sparkle.VX;
        if (sparkle.Y - (littleCircleHeight / 2) > _rect.Height)
        {
            _shapes.RemoveAt(indx);
        }
        else
        {
            // grab the cached one
            TranslateTransform t = sparkle.Transform as TranslateTransform;
            t.X = sparkle.X - (littleCircle.ActualWidth / 2);
            t.Y = sparkle.Y - (littleCircleHeight / 2);
            _bitmap.Render(littleCircle, sparkle.Transform);
        }
        indx--;

    }

    int x = _random.Next(_bitmap.PixelWidth);
    int y = 0; 

    Sparkle newsparkle = new Sparkle();
    newsparkle.X = x;
    newsparkle.Y = y;
    newsparkle.VX = _random.NextDouble() + .001;
    newsparkle.VX = (_random.Next(10) > 5 ? newsparkle.VX : newsparkle.VX * -1.0);
    newsparkle.VY = _random.NextDouble() * 5 + 1.0;
    newsparkle.Transform = new TranslateTransform() { Y = newsparkle.Y, X = newsparkle.X };

    _shapes.Add(newsparkle);
    _bitmap.Invalidate();
}

Sizing:

void MainPage_SizeChanged(object sender, SizeChangedEventArgs e)
{
    _bitmap = new WriteableBitmap((int)e.NewSize.Width, (int)e.NewSize.Height);
    _bitmap.Clear(Colors.Black);
    _rect = new Rect(0, 0, e.NewSize.Width, e.NewSize.Height);
    dest.Source = _bitmap;
}

The sparkle class:

public class Sparkle
{
    public double X { get; set; }
    public double Y { get; set; }

    public double VX { get; set; }
    public double VY { get; set; }

    public Transform Transform { get; set; }
}

And it also uses a few functions from the WriteableBitmap extension classes on CodePlex.

It doesn’t perform nearly as well as it does in stand-alone Silverlight – but it’s running in a VM on my laptop, without accelerated graphics ….. I blame my hardware.