Wednesday, September 02, 2009

Sample WritableBitmap

the image to a random color. The image is being redraw regularly so it shows a notion of “rain”. Here is the initialization:

        private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
{

Screen.Width
= ScreenWidth;
Screen.Height
= ScreenHeight;

//Criaco do object writablebitmap com o tamanho indicado.
bitmap = new WriteableBitmap(ScreenWidth, ScreenHeight);
//Indicao de qual o elemento que ira fazer a visualizao do writable bitmap.
Screen.Source = bitmap;

//registar o evento para fazer o render regular
CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
}


After initilization and on each frame we redraw the pixels randomly:

void CompositionTarget_Rendering(object sender, EventArgs e)
{
var index
= MaxScreen;

//Pintar cada pixel
while (--index > -1)
{
//cor aleatoria para cada pixel
var color = System.Convert.ToInt32(rnd.Next(0xffffff));
bitmap.Pixels[index]
= color > 0xffffff ? 0xffffff : color;
}

//força o bitmap a redesenhar
bitmap.Invalidate();
}


Regarding the XAML we use an image of a TV to give a more realistic effect:



    <Grid x:Name="LayoutRoot" Background="#FFFFFFFF">
<Image x:Name="tv" Source="tv.jpg" Margin="68,29.807,72,53.193" d:LayoutOverrides="Width, Height"/>
<Image x:Name="Screen" OpacityMask="{x:Null}" Margin="99,57,100,0" Opacity="1" VerticalAlignment="Top" Height="216" Width="390"/>
</Grid>


The result is:



clip_image002


You can download the source code here and the demo can be seen here.

We can also play with the mouse movement and make it create interferences on the TV. We need to capture the mouse movement event and act accordingly:

//Repaint the screen regularly
void CompositionTarget_Rendering(object sender, EventArgs e)
{
var index
= MaxScreen;

//Paint each bitmap pixel.
while (--index > -1)
{
if (index % (mouseLastPos.X/2 + mouseLastPos.Y/2)+rnd.Next(20) < 15)
bitmap.Pixels[index]
= 0xffffff;
//bitmap.Pixels[index] = Convert.ToInt32(mouseLastPos.X * mouseLastPos.Y+5000);
else
{
//Random color for each pixel.
var color = System.Convert.ToInt32(rnd.Next(0xffffff));
bitmap.Pixels[index]
= color > 0xffffff ? 0xffffff : color;
}
}

//force bitmap repaint
bitmap.Invalidate();
}

Final result can be seen here.

No comments: