2

I am trying to implement a gradient brush from scratch in C++ with GDI. I don't want to use GDI+ or any other graphics framework. I want the gradient to be of any direction (arbitrary angle).

My algorithm in pseudocode:

      For each pixel in x dirrection
      For each pixel in the y direction
          current position = current pixel - centre                      //translate origin 
          rotate this pixel according to the given angle
          scalingFactor =( rotated pixel + centre ) / extentDistance    //translate origin back 
          rgbColor = startColor + scalingFactor(endColor - startColor)

extentDistance is the length of the line passing from the centre of the rectangle and has gradient equal to the angle of the gradient

Ok so far so good. I can draw this and it looks nice. BUT unfortunately because of the rotation bit the rectangle corners have the wrong color. The result is perfect only for angle which are multiples of 90 degrees. The problem appears to be that the scaling factor doesn't scale over the entire size of the rectangle.

I am not sure if you got my point cz it's really hard to explain my problem without a visualisation of it.

If anyone can help or redirect me to some helpful material I'd be grateful.

George Eracleous
  • 4,278
  • 6
  • 41
  • 50
  • Posting your actual code might be more helpful. The pseudocode looks OK, so it's possible the problem lies in the details of the implementation. – Adrian McCarthy Aug 17 '11 at 16:17
  • Well, based on what I've done so far I don't think it's a problem with the actual implementation. I think the problem is my algorithm. The code works but it is not good enough due to the problem I mentioned. Therefore what I'm asking for is a formal or at least tested algorithm for achieving the gradient effect! – George Eracleous Aug 18 '11 at 07:51

1 Answers1

1

Ok guys fixed it. Apparently the problem was that when I was rotating the gradient fill (not the rectangle) I wasn't calculating the scaling factor correctly. The distance over which the gradient is scaled changes according to the gradient direction. What must be done is to find where the edge points of the rect end up after the rotation and based on that you can find the distance over which the gradient should be scaled. So basically what needs to be corrected in my algorithm is the extentDistance.

How to do it:

•Transform the coordinates of all four corners

•Find the smallest of all four x's as minX

•Find the largest of all four x's and call it maxX

•Do the same for y's.

•The distance between these two point (max and min) is the extentDistance

George Eracleous
  • 4,278
  • 6
  • 41
  • 50