views:

54

answers:

1

I am working with GDI+, the image I am working with is a 1bbp image. What i would like to do is draw a rectangle on the image and everything under that rectangle will be inverted (white pixels will become black and black pixels become white).

All of the sample code I have seen is for 8 bit RGB color scale images, and I don't think the techniques they use will work for me.

Here is the code I have so far. This is the parent control, one of the Epl2.IDrawableCommand's will be the command that does the inverting.

public class DisplayBox : UserControl
{
    (...)
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        (...)
            using (Bitmap drawnLabel = new Bitmap((int)((float)Label.LabelHeight * _ImageScaleFactor), (int)((float)Label.LableLength *(int) _ImageScaleFactor), System.Drawing.Imaging.PixelFormat.Format1bppIndexed))
            {
                using (Graphics drawBuffer = Graphics.FromImage(drawnLabel))
                {
                    (...)
                    foreach (Epl2.IDrawableCommand cmd in Label.Collection)
                    {
                        cmd.Paint(drawBuffer);
                    }
                    (...)
                }
            }
        }
    }
}
public class InvertArea : IDrawableCommand
{
    (...)
    public Rectangle InvertRectangle {get; set;}
    public void Paint(Graphics g)
    {
        throw new NotImplementedExecption();
    }
}

What should I put in the Paint(Graphic g) for this command?

+3  A: 

The trick is to draw the same image again and use a ColorMatrix that inverts the image. For example:

    protected override void OnPaint(PaintEventArgs e) {
        e.Graphics.DrawImage(mImage, Point.Empty);
        ImageAttributes ia = new ImageAttributes();
        ColorMatrix cm = new ColorMatrix();
        cm.Matrix00 = cm.Matrix11 = cm.Matrix22 = -0.99f;
        cm.Matrix40 = cm.Matrix41 = cm.Matrix42 = 0.99f;
        ia.SetColorMatrix(cm);
        var dest = new Rectangle(50, 50, 100, 100);
        e.Graphics.DrawImage(mImage, dest, dest.Left, dest.Top, 
            dest.Width, dest.Height, GraphicsUnit.Pixel, ia);
    }

Where mImage was my sample 1bpp image and I'm inverting a 100x100 rectangle at 50,50

Hans Passant