Tuesday, August 03, 2004

Draw with Inverse Color

After some research and testing, finally has figure out how to draw a rectangle using a color that is the inverse of its drawing surface. The code make use of PInvoke to GDI32 functions.

Here is the sample code :

public sealed class GDI32
public const int R2_NOT = 6;

public const int NULL_BRUSH = 5;
public const int HOLLOW_BRUSH = NULL_BRUSH;

[DllImport("gdi32.dll", EntryPoint="SetROP2")]
public static extern int SetROP2(IntPtr hDc, int fnDrawMode);

[DllImport("gdi32.dll", EntryPoint="SelectObject")]
public static extern IntPtr SelectObject(IntPtr hdc,IntPtr bmp);

[DllImport("gdi32.dll", EntryPoint="Rectangle")]
public static extern bool Rectangle(IntPtr hdc,int x, int y, int x2, int y2);

[DllImport("gdi32.dll", EntryPoint="GetStockObject")]
public static extern IntPtr GetStockObject(int fnObject);

public sealed class USER32
public static extern IntPtr GetDC(IntPtr ptr);


IntPtr p = USER32.GetDC(this.Handle); // System.Windows.Forms.Form.Handle
GDI32.SetROP2(p, GDI32.R2_NOT);
GDI32.SelectObject(p, GDI32.GetStockObject(GDI32.HOLLOW_BRUSH));
GDI32.Rectangle(p, sx, sy, cx, cy);

However, calling the code intensively will cause a performance hit. I use the code in the Winform's MouseMove event to draw the rectangle, and the performance degrades is evident. I have do some work to minimize the PInvoke call but it is still a slow code.

Labels: ,


Post a Comment

<< Home