Sunday, October 2, 2011

Writeable Bitmap on the Web

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Silverlight
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }
        System.Windows.Threading.DispatcherTimer tmr;
        System.Windows.Media.Imaging.WriteableBitmap screen;

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            screen = new System.Windows.Media.Imaging.WriteableBitmap(320, 204);
            tmr = new System.Windows.Threading.DispatcherTimer();
            tmr.Interval = System.TimeSpan.FromMilliseconds(100);
            tmr.Tick += OnTimer;
            tmr.Start();
        }
        void OnTimer(Object Sender, EventArgs args)
        {
            int px,py;
            int offset = 0;
            for (py = 0; py < 204; py++)
            {
                for (px = 0; px < 320; px++)
                {
                    screen.Pixels[offset] = 64 << 24 | 0 << 16 | 0 << 8 | 255;
                    offset++;
                }
            }
            image1.Source = screen;
        }
        private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
            tmr.Stop();
        }
        //fin.
    }
}
Open Visual Studio and choose new project C#  -> SilverLight. Make sure it's SilverLight 4. When the solution is created select the Grid and press Delete key. Then go to Toolbox select Image component place it in the IDE and make sure Stretch is equal to Fill.

 The pixel format is Alpha | Red | Green | Blue. I used Blue = 255, and Alpha = 64. This blends the background white color with the image color.

This gives us a Bitmap that can be updated 10 times a second for games and animations. For 50 updates per second set timer interval to 20 instead of 100.

Your first internet application! And it's working on my Browser Google Chrome, fantastic result. I have a book that shows a silverlight app running on Mozilla Firefox as well. Just shows how powerful and well done Visual Studio 2010 Professional really is. The Toolbox is my favorite, allows me to set up projects quickly.

Change :
screen.Pixels[offset] = 64 << 24 | 0 << 16 | 0 << 8 | 255;
to :
screen.Pixels[offset] = py << 24 | 0 << 16 | 0 << 8 | 255;
And get this :

Silverlight Website of note :          http://10rem.net/   C64 emulator, synthesizer, what else has to be said?

No comments:

Post a Comment