Drawing with opposite (inverse) colors in a winforms application

We have a winforms application (Framework v4) that displays an image (via a PictureBox) on the screen and allows you to select a rectangular area in this image. During and after selecting an image, we show the border of the selected area. This is currently being done by calling DrawRectangle .

The problem is how to choose the color of this rectangle. Regardless of the color chosen, it is always possible that it will mix with the background (image). Microsoft paint does this very well, dynamically changing colors in the "selection rectangle." This is very suitable for our application, but I do not know how to do this in winforms.

I also looked to see if there is a dash that allows the use of two colors (so that I can specify black and white as these colors, making it visible regardless of the background color), but I could not find anything like it.

Thanks in advance for your help.

+4
source share
2 answers

you can use ControlPaint methods to draw a reversible rectangle / frame

ControlPaint.FillReversibleRectangle MSDN

and

ControlPaint.DrawReversibleFrame MSDN

here is an example of a small pseudo-code example

 private void DrawReversibleRectangle(int x, int y) { // Hide the previous rectangle by calling the methods with the same parameters. var rect = GetSelectionRectangle(this.PointToScreen(this.reversibleRectStartPoint), this.PointToScreen(this.reversibleRectEndPoint)); ControlPaint.FillReversibleRectangle(rect, Color.Black); ControlPaint.DrawReversibleFrame(rect, Color.Black, FrameStyle.Dashed); this.reversibleRectEndPoint = new Point(x, y); // Draw the new rectangle by calling rect = GetSelectionRectangle(this.PointToScreen(this.reversibleRectStartPoint), this.PointToScreen(this.reversibleRectEndPoint)); ControlPaint.FillReversibleRectangle(rect, Color.Black); ControlPaint.DrawReversibleFrame(rect, Color.Black, FrameStyle.Dashed); } 
+2
source

You mentioned that an alternative solution would be to draw a dotted line in two colors, black and white, so that it is visible on any background.

Fake this by drawing a solid line in one color (for example, black), then draw a dashed line in a different color (for example, white).

Idea and code from: http://csharphelper.com/blog/2012/09/draw-two-colored-dashed-lines-that-are-visible-on-any-background-in-c/

 using (Pen pen1 = new Pen(Color.Black, 2)) { e.Graphics.DrawRectangle(pen1, rect); } using (Pen pen2 = new Pen(Color.White, 2)) { pen2.DashPattern = new float[] { 5, 5 }; e.Graphics.DrawRectangle(pen2, rect); } 
0
source

Source: https://habr.com/ru/post/1386380/


All Articles