如何裁剪图像或矩形
Posted
技术标签:
【中文标题】如何裁剪图像或矩形【英文标题】:How to crop image or rectangle 【发布时间】:2021-09-17 19:48:27 【问题描述】:我想在 Firemonkey 中裁剪图像或矩形。我该怎么做?
【问题讨论】:
图片应该告诉我们什么?为什么是断边?为什么是箭头? 【参考方案1】:下面是代码,不想乱码就下载demo吧。
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Objects;
type
TMain = class(TForm)
Image: TImage;
Rectangle_CropPos: TRectangle;
Timer_Startup: TTimer;
procedure Timer_StartupTimer(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
Private declarations
public
Public declarations
end;
var
Main: TMain;
implementation
$R *.fmx
uses Unit2;
procedure TMain.Timer_StartupTimer(Sender: TObject);
var
lBmp: TBitmap;
xScale, yScale, scale: extended;
iRect: TRect;
OffsetX, OffsetY: extended;
BmpHwRatio: extended;
DispRatio: extended;
begin
Timer_Startup.Enabled:=False;
// --------------------------
if Rectangle_CropPos.Visible then
begin
lBmp := TBitmap.Create;
try
xScale := Image.Bitmap.Width / Image.Width;
yScale := Image.Bitmap.Height / Image.Height;
if xScale > yScale
then yscale := xScale
else xscale := yScale;
lBmp.Width := round(Rectangle_CropPos.Width * xScale);
lBmp.Height := round(Rectangle_CropPos.Height * yScale);
// added offset terms to compensate for the space between
// picture and Image1 border
offsetx := (Image.Width - Image.Bitmap.Width / xscale) / 2;
offsety := (Image.Height - Image.Bitmap.Height / yscale) / 2;
// You can test without the offset calculations
// offsetx := 0;
// offsety := 0;
// offset terms added here
iRect.Left := round((Rectangle_CropPos.Position.X - offsetx) * xscale);
iRect.Top := round((Rectangle_CropPos.Position.Y - offsety) * yscale);
iRect.Width := round(Rectangle_CropPos.Width * xscale);
iRect.Height := round(Rectangle_CropPos.Height * yscale);
if iRect.Left < 0 then iRect.Left := 0;
if iRect.Top < 0 then iRect.Top := 0;
if iRect.Width < 1 then iRect.Width := 1;
if iRect.Height > (LBMp.Height-1) then iRect.Height := LBmp.Height;
lBmp.CopyFromBitmap(Image.Bitmap, iRect, 0, 0);
if (fImagePreview.Visible=False) then
fImagePreview.Show;
fImagePreview.Left:=Self.Left+Self.ClientWidth+3;
fImagePreview.Top:=Self.Top;
fImagePreview.Image.Bitmap.Assign(lBmp);
finally
FreeAndNil(lBmp);
end;
end;
else
begin
Rectangle_CropPos.Visible := True;
Rectangle_CropPos.Width := Round(Panel1.Width * 0.5);
Rectangle_CropPos.Height := Round(Rectangle_CropPos.Width * 1.41);
Rectangle_CropPos.Position.X := Round(Panel1.Width * 0.5)-(Rectangle_CropPos.Width * 0.5);
Rectangle_CropPos.Position.Y := Round(Panel1.Height * 0.5)-(Rectangle_CropPos.Height * 0.5);
end;
end;
procedure TMain.FormCreate(Sender: TObject);
begin
Timer_Startup.Enabled:=True;
end;
end.
【讨论】:
这个级别的人不能只是将代码示例转换为工作。本主题还包括由 Delphi ide 托管的可视对象。别让我厌烦。 但实际图片无关紧要,您的带有计时器和未使用变量的表单也无关紧要,相关部分没有单个评论。不需要一个文件,只需要代码。以上是关于如何裁剪图像或矩形的主要内容,如果未能解决你的问题,请参考以下文章