Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw crosshatches on a TCanvas and specify the background color

I'm trying to make a "blank" background to place an image on top of. It's not too difficult to create crosshatches by placing a TImage on a form and doing the following:

image1.Canvas.brush.Style := bsDiagCross;
image1.canvas.brush.color := clWhatever;
image1.canvas.FillRect(image1.clientrect);

This works, and I get a crosshatch pattern in clWhatever over a black background. But that's the problem. It's always black, and I can't find any way to specify a background color in case I want something other than black.

Does anyone know how to do this?

like image 824
Mason Wheeler Avatar asked Jun 27 '10 23:06

Mason Wheeler


1 Answers

The color of a hatched brush is the foreground color - the color of the hatch itself.

The background color is set separately when using hatched brushes and as far as I know isn't exposed as a property of the TCanvas and thus requires the use of the Windows GDI API SetBkColor() function.

e.g. to draw a red hatch on a white background, add a call to set the background color before drawing using the canvas brush:

image1.Canvas.brush.Style := bsDiagCross;
image1.canvas.brush.color := clRed;

SetBkColor(image1.Canvas.Handle, ColorToRGB(clWhite));
image1.canvas.FillRect(image1.clientrect);

[Update:] NOTE: It appears that in Delphi 2010 (and possibly some earlier version/s) you should call SetBKColor() AFTER setting brush properties. Internally when the canvas creates it's brush it calls SetBKColor() which tramples on any explicit calls to SetBKColor() made prior to referencing the Canvas.Brush. The timing of when the internal canvas brush is created, or the internal use of SetBkColor(), appears to have changed between Delphi 2006 (used when testing the original posting) and Delphi 2010. Whatever the reason it is clearly more reliable to call SetBKColor immediately prior to using it.

like image 98
Deltics Avatar answered Oct 19 '22 14:10

Deltics