System.Drawing.Bitmap.CreateCompatibleBitmapContext C# (CSharp) Method

CreateCompatibleBitmapContext() private method

private CreateCompatibleBitmapContext ( int width, int height, PixelFormat pixelFormat ) : CGBitmapContext
width int
height int
pixelFormat PixelFormat
return CGBitmapContext
        private CGBitmapContext CreateCompatibleBitmapContext(int width, int height, PixelFormat pixelFormat)
        {
            int bitsPerComponent, bytesPerRow;
            CGColorSpace colorSpace;
            CGImageAlphaInfo alphaInfo;
            bool premultiplied = false;
            int bitsPerPixel = 0;

            // CoreGraphics only supports a few options so we have to make do with what we have
            // https://developer.apple.com/library/mac/qa/qa1037/_index.html
            switch (pixelFormat)
            {
            case PixelFormat.Format32bppPArgb:
            case PixelFormat.DontCare:
                premultiplied = true;
                colorSpace = CGColorSpace.CreateDeviceRGB ();
                bitsPerComponent = 8;
                bitsPerPixel = 32;
                alphaInfo = CGImageAlphaInfo.PremultipliedLast;
                break;
            case PixelFormat.Format32bppArgb:
                colorSpace = CGColorSpace.CreateDeviceRGB ();
                bitsPerComponent = 8;
                bitsPerPixel = 32;
                alphaInfo = CGImageAlphaInfo.PremultipliedLast;
                break;
            case PixelFormat.Format32bppRgb:
                colorSpace = CGColorSpace.CreateDeviceRGB ();
                bitsPerComponent = 8;
                bitsPerPixel = 32;
                alphaInfo = CGImageAlphaInfo.PremultipliedLast;
                break;
            case PixelFormat.Format24bppRgb:
                colorSpace = CGColorSpace.CreateDeviceRGB ();
                bitsPerComponent = 8;
                bitsPerPixel = 32;
                alphaInfo = CGImageAlphaInfo.PremultipliedLast;
                break;
            default:
                throw new Exception ("Format not supported: " + pixelFormat);
            }

            bytesPerRow = width * bitsPerPixel/bitsPerComponent;
            int size = bytesPerRow * height;

            var bitmapBlock = Marshal.AllocHGlobal (size);
            var bitmap = new CGBitmapContext (bitmapBlock,
                                              width, height,
                                              bitsPerComponent,
                                              bytesPerRow,
                                              colorSpace,
                              alphaInfo);

            bitmap.ClearRect (new CGRect (0,0,width,height));

            //colorSpace.Dispose ();

            return bitmap;
        }

Same methods

Bitmap::CreateCompatibleBitmapContext ( int width, int height, PixelFormat pixelFormat, IntPtr pixelData ) : CGBitmapContext