Click here to Skip to main content
15,896,726 members
Articles / Desktop Programming / WPF

Another Screensaver with WPF

Rate me:
Please Sign up or sign in to vote.
4.87/5 (17 votes)
27 Jan 2012CDDL8 min read 72.3K   4.3K   63  
Lessons learnt from writing a screensaver with WPF
using System;
using System.Diagnostics;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using RZWScreenSaver.Graphics.ColorSpaces;

namespace RZWScreenSaver.Graphics{
    public class RawBitmap{
        public RawBitmap(BitmapSource bitmap){
            if (bitmap.Format != PixelFormats.Pbgra32)
                throw new NotSupportedException("Current supported pixel format is Pbgra32");

            var bytesPerPixel = (bitmap.Format.BitsPerPixel + 7) / 8;
            stride = bitmap.PixelWidth * bytesPerPixel;

            var length = bitmap.PixelHeight*stride;
            data = new byte[length];
            bitmap.CopyPixels(data, stride, 0);

            width = bitmap.PixelWidth;
            height = bitmap.PixelHeight;
            dpiX = bitmap.DpiX;
            dpiY = bitmap.DpiY;
            format = bitmap.Format;
            palette = bitmap.Palette;
        }
        public byte[] Data{
            get { return data; }
        }
        public int Stride{
            get { return stride; }
        }
        public int Height{
            get { return height; }
        }
        public int Width{
            get { return width; }
        }
        public RawBitmap CloneWithData(Rgba32 rgbData){
            Debug.Assert(format == PixelFormats.Pbgra32);
            Debug.Assert(rgbData.Width == width && rgbData.Height == height);
            var result = (RawBitmap) MemberwiseClone();
            result.data = rgbData.Data;
            return result;
        }
        public BitmapSource ToBitmap(){
            var result = BitmapSource.Create(width, height, dpiX, dpiY, format, palette, data, stride);
            Debug.Assert(!result.IsFrozen);
            Debug.Assert(result.CanFreeze);
            result.Freeze();
            return result;
        }
        byte[] data;
        readonly int stride;
        readonly int width, height;
        readonly double dpiX, dpiY;
        readonly PixelFormat format;
        readonly BitmapPalette palette;
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Common Development and Distribution License (CDDL)


Written By
Architect
Thailand Thailand
C/C++ and C# programmer.

Comments and Discussions