2006. október 1., vasárnap

How to get the RGB value of a pixel under the mouse cursor


Problem/Question/Abstract:

How can I get the hex RGB value of the pixel under the cursor? I want to be able to do this when the cursor is over an image.

Answer:

Solve 1:

Mouse movement:


procedure TForm1.ImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
  ColNumb := Image.Canvas.Pixels[X, Y]; {The image can't be a JPG}
  GetRGB(ColNumb, R, G, B);
  {Here are the RGB values you need}
end;


The GetRGB procedure:


procedure GetRGB(Col: TColor; var R, G, B: Byte);
var
  Color: $0..$FFFFFFFF;
begin
  Color := ColorToRGB(Col);
  R := ($000000FF and Color);
  G := ($0000FF00 and Color) shr 8;
  B := ($00FF0000 and Color) shr 16;
end;


Solve 2:

var
  MyColor: TColor;
begin
  MyColor := Image1.Canvas.Pixels[x, y];
  Label1.Caption := format('Red: %d; Green: %d; Blue:%d',
    [GetRValue(MyColor), GetGValue(MyColor), GetBValue(MyColor)]);
end;


Solve 3:

function DesktopColor(const x, y: integer): TColor;
var
  c: TCanvas;
begin
  c := TCanvas.create;
  c.handle := GetWindowDC(GetDesktopWindow);
  result := getpixel(c.handle, x, y);
  c.free;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  pos: TPoint;
begin
  GetCursorPos(Pos);
  Panel1.Color := DesktopColor(pos.x, pos.y);
end;

Nincsenek megjegyzések:

Megjegyzés küldése