Skip to content

Instantly share code, notes, and snippets.

@viniciusfbb
Last active August 18, 2023 06:55
Show Gist options
  • Save viniciusfbb/0adbed0f95f2d9cff245a3e209d2a2f0 to your computer and use it in GitHub Desktop.
Save viniciusfbb/0adbed0f95f2d9cff245a3e209d2a2f0 to your computer and use it in GitHub Desktop.
Fit and crop a image using Skia4Delphi
unit Skia.FitAndCrop;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Math,
System.Math.Vectors, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics,
FMX.Objects, Skia, Skia.FMX;
type
TForm1 = class(TForm)
SkPaintBox1: TSkPaintBox;
procedure SkPaintBox1Draw(ASender: TObject; const ACanvas: ISkCanvas;
const ADest: TRectF; const AOpacity: Single);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
procedure TForm1.SkPaintBox1Draw(ASender: TObject; const ACanvas: ISkCanvas;
const ADest: TRectF; const AOpacity: Single);
procedure DrawImageFitCrop(const ACanvas: ISkCanvas; const ADest: TRectF; const AImage: ISkImage);
var
LRect: TRectF;
LRatio: Double;
begin
LRect := TRectF.Create(0, 0, AImage.Width, AImage.Height);
if (ADest.Width > 0) and (ADest.Height > 0) then
begin
if (LRect.Width / ADest.Width) < (LRect.Height / ADest.Height) then
LRatio := LRect.Width / ADest.Width
else
LRatio := LRect.Height / ADest.Height;
ACanvas.Save;
try
if not SameValue(LRatio, 0, TEpsilon.Position) then
begin
LRect := TRectF.Create(0, 0, Round(LRect.Width / LRatio), Round(LRect.Height / LRatio));
RectCenter(LRect, ADest);
ACanvas.Translate(LRect.Left, LRect.Top);
ACanvas.Scale(LRect.Width / AImage.Width, LRect.Height / AImage.Height);
end;
ACanvas.DrawImage(AImage, 0, 0, TSkSamplingOptions.High);
finally
ACanvas.Restore;
end;
end;
end;
var
LImage: ISkImage;
LRoundRect: ISkRoundRect;
begin
LImage := TSkImage.MakeFromEncodedFile('..\..\shrek.jpg');
ACanvas.Save;
try
// Add round corners to draws. If you don't want it, just remove the line below.
LRoundRect := TSkRoundRect.Create(ADest, 48, 48);
ACanvas.ClipRoundRect(LRoundRect, TSkClipOp.Intersect, True);
DrawImageFitCrop(ACanvas, ADest, LImage);
finally
ACanvas.Restore;
end;
end;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment