判断一个点是否在矩形内PtInRegion-解决PtInRect不能正确判断不同形式TRent的情况

 

PtInRegion

API说明:

BOOL PtInRegion(

    HRGN hrgn, // handle of region
    int X, // x-coordinate of point
    int Y // y-coordinate of point
   );

Parameters

hrgn

Identifies the region to be examined.

X

Specifies the x-coordinate of the point.

Y

Specifies the y-coordinate of the point.

Return Values

If the specified point is in the region, the return value is nonzero.

Delphi代码:

unit Unit2;

interface

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

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);
    procedure FormDestroy(Sender: TObject);
private
    { Private declarations }
    p1, p2: TPoint; //p1, p2构成矩形
    FRect: TRect;
    FRgn: HRGN;
public
    { Public declarations }
end;

var
Form2: TForm2;

implementation

{$R *.dfm}

procedure TForm2.FormCreate(Sender: TObject);
begin
//从p1点向p2点方向画矩形(两个点画矩形有4中可能的情况:即p1为左上,左下,右下,右上坐标点)
{$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;

FRgn := CreateRectRgnIndirect(FRect);
end;

procedure TForm2.FormDestroy(Sender: TObject);
begin
DeleteObject(FRgn);
end;

procedure TForm2.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if PtInRegion(FRgn, X, Y) 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、付费专栏及课程。

余额充值