Search code examples
delphigraphicsdelphi-xe2tcanvas

How can I replace color on TCanvas on Delphi?


How can I replace color on TCanvas on Delphi XE2? The following code works incredibly slow:

  for y := ARect.Top to ARect.Top + ARect.Height - 1 do
    for x := ARect.Left to ARect.Left + ARect.Width - 1 do
      if Canvas.Pixels[x, y] = FixedColor then
        Canvas.Pixels[x, y] := Canvas.Pixels[ARect.Left, ARect.Top];

Solution

  • var
      aBitmap: TBitmap;
      x, y: Integer;
      aPixel: PRGBTriple;
    
     ...
    
      aBitmap := TBitmap.Create;
      try
        aBitmap.PixelFormat := pf24bit;
        aBitmap.Height := ARect.Height;
        aBitmap.Width := ARect.Width;
        aBitmap.Canvas.CopyRect(TRect.Create(0, 0, aBitmap.Width, aBitmap.Height), Canvas, ARect);
        for y := 0 to aBitmap.Height - 1 do
          for x := 0 to aBitmap.Width - 1 do
          begin
            aPixel := aBitmap.ScanLine[y];
            Inc(aPixel, x);
            if (aPixel^.rgbtRed = GetRValue(FixedColor)) and (aPixel^.rgbtGreen = GetGValue(FixedColor)) and (aPixel^.rgbtBlue = GetBValue(FixedColor)) then
              aPixel^ := PRGBTriple(aBitmap.ScanLine[y])^;
          end;
        Canvas.Draw(ARect.Left, ARect.Top, aBitmap);
      finally
        aBitmap.Free;
      end;