Saturday, February 19, 2011

Changing pictures by clicking on the TImage component

Q : I want to change picture loaded into Image1 - from one called 1active.png to second called 1inactive.png and vice versa by clicking on the Image1 component.
Is there any way to do it?

A :
ingredients:
  • 1 boolean variable
  • 1 TImage component
  • 1 line added to form OnCreate event handler
  • 1 TImage.OnClick event handler

instructions:
1) Create a boolean variable in the private section of your form declaration. For this example, call this variable fImageActive.
private
  fImageActive
: boolean;
2) From the form designer, drop (or select an existing) TImage component on the form and select the onClick event, and double click to switch into editing. Then add the following code:
  fImageActive := not fImageActive;
 
if fImageActive then
   
Image1.Picture.LoadFromFile('1active.png')
 
else
   
Image1.Picture.LoadFromFile('1inactive.png')
3) From the form designer, find the picture property and click the ellipsis to load the 1active.png file for starters.
4) Click on the form, find the event named "OnCreate", double click and add the following code (this will set the initial state):
  fImageActive := true;
 
---------------------------------------------------------------------------------
 
I assume you are using D2009 as you can load a png file in Image1.
If you don't want to distribute your images along with your application (as above solution implies), you have to include them as resources:
Add the png to your project: Use menu "Project | Resources..." and add the files.
Name them accordingly to get something like:
 1active.png    RCData  PngImage_Active  
 
1inactive.png  RCData  PngImage_Inactive
In your Click event, you'll need some state indicator to know which one to display (like above).
I used the Image1.hint to tell which image is loaded (quick and dirty, for demo purpose).
Use the LoadImgFromPngResource proc below to load the appropriate png image:
procedure LoadImgFromPngResource(const AResName: string; DestImage: TImage);
var
  png
: TPngImage;
begin
  png
:= TPngImage.Create;
 
try
    png
.LoadFromResourceName(HInstance, AResName);
   
DestImage.Picture.Assign(png);
 
finally
    png
.Free;
 
end;
end;

procedure
TForm4.Image1Click(Sender: TObject);
begin
 
if Image1.Hint <> 'Active' then
 
begin
   
LoadImgFromPngResource('PngImage_Active', Image1);
   
Image1.Hint := 'Active';
 
end
 
else
 
begin
   
LoadImgFromPngResource('PngImage_Inactive', Image1);
   
Image1.Hint := 'Inactive';
 
end;
end;
 
 
 

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Kang Iwan K-sev | Thank's for your visit To My Site - Ridwan Mulyana | Cibeureum