你只需要几个减法和除法:
function TForm1.ClientToBitmap(const P: TPoint): TPoint;
var
cW, cH: Integer; // width and height of control
bW, bH: Integer; // width and height of bitmap
Origin: TPointF; // top-left pixel of bitmap in the control
ZoomW, ZoomH: Double; // required zoom factor to make bitmap fit horisontally or vertically
Zoom: Double; // zoom factor
begin
cW := Image1.Width;
cH := Image1.Height;
bW := Image1.Picture.Bitmap.Width;
bH := Image1.Picture.Bitmap.Height;
ZoomW := cW/bW;
ZoomH := cH/bH;
Zoom := Min(ZoomW, ZoomH);
Origin.X := (cW - bW*Zoom) / 2;
Origin.Y := (cH - bH*Zoom) / 2;
Result.X := Round((P.X - Origin.X) / Zoom);
Result.Y := Round((P.Y - Origin.Y) / Zoom);
end;
现在:
procedure TForm1.Image1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
with ClientToBitmap(Point(X, Y)) do
begin
Image1.Picture.Bitmap.Canvas.Pixels[X - 1, Y - 1] := clBlack;
Image1.Picture.Bitmap.Canvas.Pixels[X - 1, Y] := clBlack;
Image1.Picture.Bitmap.Canvas.Pixels[X - 1, Y + 1] := clBlack;
Image1.Picture.Bitmap.Canvas.Pixels[X, Y - 1] := clBlack;
Image1.Picture.Bitmap.Canvas.Pixels[X, Y] := clBlack;
Image1.Picture.Bitmap.Canvas.Pixels[X, Y + 1] := clBlack;
Image1.Picture.Bitmap.Canvas.Pixels[X + 1, Y - 1] := clBlack;
Image1.Picture.Bitmap.Canvas.Pixels[X + 1, Y] := clBlack;
Image1.Picture.Bitmap.Canvas.Pixels[X + 1, Y + 1] := clBlack;
end;
end;