5

I'm trying to run some slightly-modified code from an MSDN article as part of a school project. The goal is to use a colormatrix to recolor a bitmap in a picture box. Here's my code:

        float[][] colorMatrixElements = { 
        new float[] {rScale,  0,  0,  0},        
        new float[] {0,  gScale,  0,  0},        
        new float[] {0,  0,  bScale,  0},        
        new float[] {0,  0,  0,  1}};

        ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

where rScale, gScale, and bScale are floats with values from 0.0f to 1. The original MSDN article is here: https://msdn.microsoft.com/en-us/library/6tf7sa87%28v=vs.110%29.aspx

When it gets down to the last line, "ColorMatrix colorMatrix = new... " my code hits a runtime error. In the debugger, I get colorMatrixElements as a float[4][]. As if it's not a 4x4 array. Did I botch something in my copy-paste job, or am I just not understanding how C# handles 2D arrays?

Thanks for the help.

Micah
  • 514
  • 3
  • 11

1 Answers1

4

Per the very page you link to, you need to pass a 5 by 5 array to that constructor. You are passing a 4 by 4 array, so naturally you get an IndexOutOfBoundsException.

Try

    float[][] colorMatrixElements = { 
    new float[] {rScale,  0,    0,    0,  0},        
    new float[] {0,    gScale,  0,    0,  0},        
    new float[] {0,    0,    bScale,  0,  0},        
    new float[] {0,    0,    0,       1,  0},
    new float[] {0,    0,    0,       0,  1}
       };

    ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
AakashM
  • 62,551
  • 17
  • 151
  • 186
  • That worked out well. It'll take a bit of tampering in the larger scheme of my project to do what I need to do, but it compiles now. Thanks for the answer! – Micah Dec 04 '15 at 11:01