gpt4 book ai didi

delphi - 限制 TControl 的比例

转载 作者:行者123 更新时间:2023-12-03 18:08:23 25 4
gpt4 key购买 nike

如何为 TControl(在我的例子中是 TGraphicControl)创建约束比例
因此,如果我更改它的 Width - Height 将改变比例(反之亦然)。
此外,如果我设置 BoundsRect 控件应保持比例。在我的控件中,我有一个 AspectRatio: TPoint 属性,设置:

AspectRatio.X := 4;
AspectRatio.Y := 3;

现在我的 AspectRatioFactor = 4/3。这个比例应该一直保持。

如何做到这一点?

最佳答案

unit Unit1;

interface

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

type
TPanel = Class(ExtCtrls.TPanel)
private
FAspectRatio: TPoint;
procedure SetAspectRatio(const Value: TPoint);
public
constructor Create(AOwner: TComponent); override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
property AspectRatio: TPoint read FAspectRatio write SetAspectRatio;
end;

TForm1 = class(TForm)
Panel1: TPanel;
Button1: TButton;
Button2: TButton;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
end;

var
Form1: TForm1;

implementation

{$R *.dfm}
{ TPanel }

constructor TPanel.Create(AOwner: TComponent);
begin
inherited;
FAspectRatio.X := 4;
FAspectRatio.Y := 3;
end;

procedure TPanel.SetAspectRatio(const Value: TPoint);
begin
FAspectRatio := Value;
AdjustSize;
end;

procedure TPanel.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
var
vh: Double;
begin
if FAspectRatio.Y <> 0 then
begin
vh := FAspectRatio.X / FAspectRatio.Y;
if Round(AHeight * vh) <> AWidth then
begin
if AWidth <> Width then
AHeight := Round(AWidth / vh)
else
AWidth := Round(AHeight * vh);
end;
end;
inherited;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
Panel1.Width := 101;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
Panel1.Height := 101;
end;

procedure TForm1.Button3Click(Sender: TObject);
var
p: TPoint;
begin
p.X := 5;
p.Y := 3;
Panel1.AspectRatio := p;
end;

end.

重写 Setbounds 将确保保持给定的 AspectRatio。
AspectRatio 的 Setter 中的 AdjustSize 将确保 AspectRatio 的更改立即应用。
按钮事件仅用于演示。

关于delphi - 限制 TControl 的比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14092962/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com