Reputation: 2593
Trying to add a background image to a TGraphicControl.
TCard(TGraphicControl)
Private
BitMap1:TBitMap; {Used to store a card image}
Public
procedure SetBitmap(image: TBitmap);
......
procedure TCard.SetBitmap(image: TBitmap);
begin
bitmap1 := Tbitmap.create();
bitmap1.Assign(image);
canvas.draw(0,0,bitmap1);
end;
On Form 1 button click , I want to add the image to the tcard component
procedure TForm1.Button1Click(Sender: TObject);
var
image : Tbitmap;
jpg: TJpegImage;
begin
image := TBitmap.create();
jpg := Tjpegimage.Create();
jpg.LoadFromFile(dir+'\pics\backcard.jpg');
image.Assign(jpg);
card1.setbitmap(image);
card1.Repaint;
image.Destroy;
jpg.Destroy;
end;
When I run this nothing happens. How do I get this image to the background of the TCard component?
Upvotes: 4
Views: 1775
Reputation: 125749
Here's an example of setting a background image for a TGraphicControl
descendant, and an example of using it (it uses a TBitmap
in the form's OnCreate
, and a TJpegImage
in the Button1Click
to demonstrate both). It requires nothing but a new blank VCL forms application with a single TButton
located on it to start.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Jpeg, StdCtrls;
type
TCard = class(TGraphicControl)
private
FBackGround: TBitmap;
procedure SetBackground(Value: TBitmap); overload;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Paint; override;
published
property BackGround: TBitmap read FBackGround write SetBackground;
end;
TForm1 = class(TForm)
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
FCard: TCard;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TCard }
constructor TCard.Create(AOwner: TComponent);
begin
inherited;
FBackGround := TBitmap.Create;
end;
destructor TCard.Destroy;
begin
FBackground.Free;
inherited;
end;
procedure TCard.Paint;
begin
inherited;
Self.Canvas.StretchDraw(Self.ClientRect, FBackGround);
end;
procedure TCard.SetBackground(Value: TBitmap);
begin
FBackGround.Assign(Value);
//Self.SetBounds(Left, Top, FBackGround.Width, FBackGround.Height);
Invalidate;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Image: TJPEGImage;
Bmp: TBitmap;
begin
Image := TJPEGImage.Create;
Bmp := TBitmap.Create;
try
Image.LoadFromFile(PathToSomeJPEGFile);
Bmp.Assign(Image);
FCard.BackGround := Bmp;
finally
Bmp.Free;
Image.Free;
end;
end;
procedure TForm4.FormCreate(Sender: TObject);
var
Bmp: TBitmap;
begin
FCard := TCard.Create(Self);
FCard.Parent := Self;
Bmp := TBitmap.Create;
try
// Load a standard image from the backgrounds folder (D2007).
Bmp.LoadFromFile('C:\Program Files (x86)\Common Files\CodeGear Shared\Images\BackGrnd\GREENBAR.BMP');
FCard.BackGround := Bmp;
finally
Bmp.Free;
end;
end;
end.
Upvotes: 5