Today, Delphi is one of the popular desktop programming tool. There are thousand even million programmer in this world using delphi as their favorit tool. This site try to collect the examples, tips and tricks of Delphi programming. We collect, test them and redistribute the collection of delphi programming for you.

Crop Image with Drag the Mouse

Author: admin | Category: Graphic, Tips and Tricks

//This is how we can crop image by dragging mouse over the image
//This example needs Image (TImage) and Button (TButton)
//Drag your mouse over Image1 then click Button1
 
unit Unit1;
 
interface
 
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ExtCtrls, StdCtrls;
 
type
  TForm1 = class(TForm)
    Button1: TButton;
    Image1: TImage;
    procedure Image1MouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure Image1MouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    procedure Image1MouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
 
var
  Form1: TForm1;
 
implementation
 
{$R *.dfm}
 
var
  PDown             : TPoint;
  PActually         : TPoint;
  MouseIsDown       : Boolean;
 
procedure TForm1.Image1MouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  PDown := Point(x, y);
  PActually := Point(x, y);
  MouseIsDown := TRUE;
  Image1.Canvas.DrawFocusRect(Rect(x, y, x, y));
end;
 
procedure TForm1.Image1MouseMove(Sender: TObject; Shift: TShiftState; X,
  Y: Integer);
begin
  if MouseIsDown then
  begin
    Image1.Canvas.DrawFocusRect(Rect(PDown.x, PDown.y, PActually.x,PActually.y));
    PActually := Point(x, y);
    Image1.Canvas.DrawFocusRect(Rect(PDown.x, PDown.y, x, y));
  end;
end;
 
procedure TForm1.Image1MouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  Image1.Canvas.DrawFocusRect(Rect(PDown.x, PDown.y, PActually.x, PActually.y));
  Image1.Canvas.DrawFocusRect(Rect(PDown.x, PDown.y, x, y));
  PActually := Point(x, y);
  MouseIsDown := FALSE;
end;
 
procedure TForm1.Button1Click(Sender: TObject);
var
  TmpBmp            : TBitmap;
begin
  Image1.Canvas.DrawFocusRect(Rect(PDown.x, PDown.y, PActually.x, PActually.y));
  TmpBmp := TBitmap.Create;
  with TmpBmp do
  try
    Width := Round(abs(PActually.x - PDown.x));
    Height := Round(abs(PActually.y - PDown.y));
    BitBlt(Canvas.Handle, 0, 0, Width, Height, Image1.Canvas.Handle, PDown.x,
      PDown.y, SRCCOPY);
    Image1.AutoSize := TRUE;
    Image1.Picture.Bitmap.Assign(TmpBmp);
  finally
    Free;
  end;
end;
 
end.

Tags: , ,