| Register
Saturday, May 17, 2008   

Display Images w/a Datagrid Cell Renderer

Created By  Chris Bizzell, at  10/8/2004 - 28 comments.

Click to view this author's website.

Previously, I demonstrated the creation of a simple photo gallery that read the contents of a folder on a web server and displayed the returned images in dynamically created MovieClips inside of Flash (see "Flash and ASP").

Today, I am going to extend on this and demonstrate another technique that utilizes a Cold Fusion CFC to read a web folder's content and the Flash Datagrid Component to display the returned thumbnails. All of the transactions between Flash and the CFC will be handled via Flash Remoting.

View Working Example

Building our Image List

Most of the time, people relate Flash Remoting with returning information from a database. However it can also be used to leverage other Cold Fusion methods. For this application
we will build a CFC that utilizes the cfdirectory tag. Here is the component:

Basically all this CFC does is create an array of file information named myThumbs. The file information returned to Flash is very comprehensive but we will be most concerned with the first item in our array: name. Save this file as slides.cfc.

Flash Front End

Building our image list was easy. Now to the Flash side of the equation.
First of all we need to connect to our service: slides.cfc as so:

#include "NetServices.as" 
// Connect to the gateway and create a service object 
if (connected == null) { 
  connected = true; 
NetServices.setDefaultGatewayUrl("http://www.bizwerk.net/flashservices/gateway");
  var my_conn = NetServices.createGatewayConnection(); 
  var myService = my_conn.getService("slides",this); 
  trace ("connection made");
}

Test your movie and you should see the words "connection made" in the
output window.

Next we need to call our service and handle the results returned from our CFC.
Add a datagrid component to the stage and give it an instance name of myDataGrid_dg.
Add a new layer to the timeline and name it actions. Select frame one of this layer and
attach the following code:

function getThumbs_Result (result_rs) { 
  var temp = ""; 
  temp +=  result_rs.getLength(); 
  trace(temp);
  myDataGrid_dg.dataProvider = result_rs;
//The array passed from our CFC has a lot
//of stuff in it that we do not need
//we only want the image name which appears
//in column one so we remove the other columns
myDataGrid_dg.removeColumnAt(1);
myDataGrid_dg.removeColumnAt(2);
myDataGrid_dg.removeColumnAt(3);
myDataGrid_dg.removeColumnAt(4);
myDataGrid_dg.removeColumnAt(1);
myDataGrid_dg.removeColumnAt(1);
myDataGrid_dg.getColumnAt(0).headerText = "Thumbnail Image";
myDataGrid_dg.setStyle("alternatingRowColors",[0xD8F9FC,0xeeeee2]); 
}

 myService.getThumbs();

Test your movie and see that the names of your image files appear in the grid.
Now we need to use the returned image names to load the corresponding jpegs
into our datagrid.

Enter the Cell Renderer

Cell Renderers have two parts; a MovieClip and the Class that tells the MovieClip what
to do. We will employ a cell renderer here to enable our datagrid to display images.

The first thing we need to do is create our MovieClip. Go to the Library and click on the plus sign. Choose new MovieClip and give it an name of imageCellRender. Now click on the linkage Export for Actionscript. The identifier field will automatically populate but you will need to type in the AS 2.0 class of imageCellRender - imageCellRender will be the name of our .as file that we will write next. Click OK.

Next create an empty MovieClip manually and name it imageCont and click OK. Re-open our imageCellRender MovieClip and place an instance of our imageCont MovieClip on frame one. Give this instance a name of img .We will load our images into this empty MovieClip.

We are done with our Flash Movie for the time being.

Create our Actionscript File

Now we need to create our new Actionscript Class and name it imageCellRender.as. Save this file in the same directory as our Flash Movie. This AS file will control the actions of our MovieClip imageCellRender in our Flash movie. It can do this because we set AS 2.0 linkage
when we created the MovieClip imageCellRender.

Go to Flash and choose File .. New .. Actionscript File. You are presented with an editor that allows you to type in you actionscript code. Type the following:

import mx.core.UIComponent;
class imageCellRender extends UIComponent {
	var img:MovieClip;
	var url:String;
	var getDataLabel:Function;
	function IconCellRenderer() {
		
	}
	function createChildren(Void):Void {
		size();
	}
	// the setValue function is called  when the component
	// is first drawn and whenever a user interacts with the datagrid
	function setValue(str:String, item:Object, sel:Boolean):Void {
		img._visible = (item[getDataLabel()] != undefined);
		// do not render a cell if the data label is undefined
		if(item[getDataLabel()] != undefined){
		// do not re-draw cell if data label is unchanged
		if(item[getDataLabel()] != this.url){
		// load the appropriate jpg into our img MovieClip instance
			img.loadMovie(item[getDataLabel()]);
	// if the user interacts with a cell we need to see if the image needs to be redrawn
	// if this.url is unchanged this code tells the datagrid not to redraw
			this.onEnterFrame = function(){
	//make sure that the image has fully loaded
	//set this.url to image name returned for the corresponding cell
	//so that we can check if data label has changed
				if(img.getBytesLoaded() >= img.getBytesTotal()) {
					this.url = item[getDataLabel()];
				}
				}
				}
			}
		}
// use the size function to postion our empty MovieClip img
	function size(Void) : Void
	{
		img._y = -48;
		img._x = 40;
	}	
}

The cell renderer script is commented with all of the explanations you should need.
Again, save this AS file as imageCellRender.as in the same directory as your Flash movie.

Putting our Cell Renderer to Work

We now have our cell renderer script complete. All that is left is to put it to work in our Flash movie. Re-open our datagrid_iamges.fla file and open our actions code. If you tested your Flash application earlier, you will remember that the datagrid listed the names of our image files. We need to tweak our code so that column one renders the images themselves and not just their names. Inside the function that handles our remoting results add the following line right above the code that removes our unwanted columns:

myDataGrid_dg.getColumnAt(0).cellRenderer="imageCellRender";

All this does is tell the datagrid to use our AS class that we created in the imageCellRenderer.as file to redender the contents of column one. To make sure our datagrid properly displays the images select it and give it a rowHeight of 120. Now test your movie and you should see the images fill you grid.

To finish this example place a loader component on the stage and give it an instance name of cont and place a progress bar component on the stage and give it an instance name of pBar.
Lastly, attach the following code to frame one of the main timeline:

function getDetails(){
counter = myDataGrid_dg.getSelectedIndex();
_root.pic_name.text = myDataGrid_dg.getItemAt(counter).Name;
cont.autoLoad = false;
cont.contentPath = myDataGrid_dg.getItemAt(counter).Name;
pBar.source = cont;
cont.load();
}

myDataGrid_dg.addEventListener("cellPress", getDetails );

This code gets the selection from the datagrid and load the corresponding image into our loader component. The progress bar monitors the loading of the image.

I hope that this will help you in your development of RIA's. Being able to extend the existing components is a powerful tool and now you hopefully have a better understanding of how to start.

Need Professional Help For Your ActionScript Project?
ActionScript.com Consulting Services provide top quality professional ActionScript consulting to businesses around the globe. If you have a professional project in need to world-class talent, tell us about your project by requesting a quote today.

Reader Comments

  1. Chad Castanheiro  Replied:
    ( 10/18/2004 At 12:33 AM)

    How would you rewrite your CFC script in PHP?

  2. Jason Lampitt  Replied:
    ( 10/22/2004 At 3:28 AM)

    Wow! This is great! I'm going to step through this article tonight and apply the concepts to my project. Thanks for your efforts!

  3. egoldy  Replied:
    ( 11/3/2004 At 11:47 AM)

    I also want to know How to rewrite your CFC script in PHP .

  4. Michael  Replied:
    ( 11/7/2004 At 5:59 AM)

    I would also like to know how to rewrite your CFC script in PHP.

  5. pnacelli  Replied:
    ( 11/9/2004 At 12:44 AM)

    how would you create a cell renderer class with a radio button group with x numbers of buttons?
    This would allow for dynamic score sheets within a data grid...

  6. Murali.K  Replied:
    ( 11/16/2004 At 3:17 PM)

    i have 20 images , i want display these images one by one it's visible is 3 seconds any body know this how to do this

  7. cvb  Replied:
    ( 11/19/2004 At 12:06 AM)

    There is an article on macromedias site that shows some more cell renderer examples:
    http://www.macromedia.com/devnet/mx/flash/articles/v2component_migration_print.html
    Flash-db.com also has some information

  8. Rayson  Replied:
    ( 12/9/2004 At 2:14 AM)

    hi,
    Does this sample requires Flash Remoting MX?
    thx
    Rayson

  9. Tommy  Replied:
    ( 1/14/2005 At 8:14 PM)

    HI TEAM
    Thanksfor the article!
    I ran it and all works well 'cept that I get no thumb in the grid. The image loads on click but no image is displayed
    Thanks@!

  10. Tommy  Replied:
    ( 1/14/2005 At 8:48 PM)

    What goes in the
    IconCellRenderer(){} function?
    It is blank

  11. Michael  Replied:
    ( 1/19/2005 At 5:53 PM)

    Hi,
    I strictly followed the tutorial but I cannot explain why the thumbnails don't load centered.
    I checked and changed the symbol position's movieclips but it didn't change anything.
    Thumbnails always load into the center of the cells but from their right-upon corner ( not the center, like in the online-demo). Why is that ?
    Thanks in advance, from Spain, Michael

  12. socrate  Replied:
    ( 4/3/2005 At 7:21 AM)

    I can’t get mine to work. I can get the "connection made" trace to appear in the output panel but when I try to test it for the second time (when putting “function getThumbs_Results” in the first frame) none of the files appears in the Datagrid. I changed the DefaultGatewayUrl to http://localhost/flashservices/gateway . I also changed the directory path pointing to the jpegs in the directory. Please help. Thanks

  13. Bob  Replied:
    ( 4/9/2005 At 12:24 PM)

    I am another person who would love a PHP version of the ASP tutorial

  14. jaturapornchai  Replied:
    ( 4/13/2005 At 11:43 AM)

    demo Java webservice + Flash

  15. flash8actionscript  Replied:
    ( 4/20/2005 At 4:28 AM)

    Thanks for the tutorial.
    It works perfectly for me, except that I have about 50 rows in my grid and when I drag the scrollbar to the bottom, the pics and the rows are very out-of-synch.
    Any way to prevent the wrong picture from displaying with the wrong row when the scrollbar is dragged quickly? It is critical for my application that the item the user is viewing is in synch with the correct row to avoid a misunderstanding.
    Thanks.

  16. Sajeer,M  Replied:
    ( 5/15/2005 At 6:53 PM)

    Hi,
    How we catch jpg from a directory plese send me a mail to this id sajeerm@yahoo.com...
    my requirement is i want to change picture every 30 seconds... linkable to another page....

  17. zbaskus  Replied:
    ( 5/21/2005 At 4:19 AM)

    http://www.bizwerk.net/datagrid_images/remote_thumbs.fla

  18. kliff  Replied:
    ( 5/23/2005 At 5:02 PM)

    Very newb to actionscript, I'm building something similar, problem is : want to load images dynamically respecting their actual size, like successive img tags in html.
    embeded img tags in textarea wont work.
    _height of movieclip after img loading neither.
    Is there a way to calculate the image size
    (something else that reading the jpg in binary mode yet i'm not sure actionscript allows this :/)

  19. Kliff  Replied:
    ( 5/23/2005 At 5:33 PM)

    found the solution here :
    http://www.flashdevils.com/showthread.php?s=&threadid=188640

  20. sean  Replied:
    ( 7/11/2005 At 8:36 AM)

    Anyone know how to have both pictures AND text in the same box of a datagrid? Looking to have subtitles under pics...
    TIA

  21. new name  Replied:
    ( 8/25/2005 At 5:44 PM)

    How do you specify different location for the images, I mean different path, e.g. the images could be located on the server somewhere.
    The tutorial was great apart from the above comment.
    Thank you

  22. Kraegan  Replied:
    ( 10/24/2005 At 7:52 PM)

    OK, you make this look easy. Too easy. I'll give it a shot.

  23. Huong  Replied:
    ( 10/28/2005 At 1:50 PM)

    I have some images (jpeg or bitmap), how can I display them in many ways like slides be shown? Please help me! Thank you in advanced.

  24. Hendra Diyana  Replied:
    ( 12/5/2005 At 1:38 PM)

    How to save some frame to be come a image or bitmap to database access with flash MX?

  25. Andre Scott  Replied:
    ( 12/21/2005 At 8:32 PM)

    Dear Sir,
    I'm using a DataGrid in which I would like the first item in the list to be selected with the textSelected color active. So far, I'm only getting the background color of the selected item.
    This is what I have so far.
    _root.newPageType4["dropList"+ID].selectedIndex = 0;
    _root.newPageType4["dropList"+ID].setStyle("textSelectedColor", 0xffffff);
    _root.newPageType4["dropList"+ID].setStyle("selectionColor", 0x860082);

  26. JB  Replied:
    ( 12/24/2005 At 3:49 AM)

    any one get this to work with Flash 8

  27. Sathish  Replied:
    ( 7/16/2006 At 4:06 AM)

    will it work as normal swf or coldfusion required?

  28. Carlos S.  Replied:
    ( 7/31/2006 At 7:18 AM)

    This is a great hack!
    I'm building a "Who's Online?" type of app on a portal site, using flash pro 8.
    I'm using aspx to pass xml data in for user info.
    And dynamically calling my images, by parsing the image url string from the user data.

    AND IT WORKS@!

    BUT, is there anyway to avoid it reloading every image every time I scroll through the datagrid?
    I thought at first it was something i mis-coded.
    But i noticed your example does it too.

    I tried a simple condition to try stopping it once it after the first pass..
    e.g.

    {pseudo_code}
    gate = 0;
    while gate=0, load the image
    and then increment gate.
    {/pseudo_code}

    this worked... until i scrolled the datagrid..
    then i noticed each new record that came into view just recycled the images i just saw, in the same order. not refreshing the list, obviously.

    Can anyone explain exactly why it needs to reload the images?
    Also, does Flash or the browser cache these loaded images, or is it hitting the server on each refresh?

    thanks, and great site!

Login to post your comments. If you do not have an account with us please Register.
Copyright 2005 by ActionScript, Inc.   |  Privacy Statement  |  Terms Of Use  |  ActionScript Client Extranet