判断一个点是否在矩形内PtInRect

 

BOOL PtInRect(

    CONST RECT *lprc, // address of structure with rectangle
    POINT pt // structure with point
   );

Parameters

lprc

Points to a RECT structure that contains the specified rectangle.

pt

Specifies a POINT structure that contains the specified point.

Return Values

If the specified point lies within the rectangle, the return value is nonzero.

该API在使用时的缺陷为不能够满足任意TRect,都能准确判断任意一点p是否在这个TRect上。
从p1点向p2点方向画矩形(两个点画矩形有4中可能的情况:即p1为左上,左下,右下,右上坐标点)
下面代码的编译开关请至于不同状态进行调试。下一篇文章会用另一个API解决该问题。

Delphi代码:

unit Unit2;

interface

{$DEFINE LEFTBOTTOM}   //注释调此编译开关 PtInRect不能正确判断在该区域的点

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;

type
TForm2 = class(TForm)
    procedure FormCreate(Sender: TObject);
    procedure FormPaint(Sender: TObject);
    procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
private
    { Private declarations }
    p1, p2: TPoint; //p1, p2构成矩形
    FRect: TRect;
public
    { Public declarations }
end;

var
Form2: TForm2;

implementation

{$R *.dfm}

procedure TForm2.FormCreate(Sender: TObject);
begin
//从p1点向p2点方向画矩形
{$IFDEF LEFTBOTTOM}
//p1为左下坐标,此时PtInRect能够正确判断在该区域的点
p1.X := 30;
p1.Y := 30;
p2.X := 200;
p2.Y := 110;
{$ELSE}
//p1为右上坐标,此时PtInRect不能正确判断在该区域的点
p1.X := 200;
p1.Y := 110;
p2.X := 30;
p2.Y := 30;
{$ENDIF}
FRect.Left := p1.X;
FRect.Right := p2.x;
FRect.Top   := p1.y;
FRect.Bottom:= p2.y;
end;

procedure TForm2.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
p: TPoint;
begin
p.X := x;
p.Y := y;
if PtInRect(FRect, p) then
    ShowMessage('该点在矩形区域内');
end;

procedure TForm2.FormPaint(Sender: TObject);
begin
Canvas.Rectangle(FRect);
end;

end.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值