Listen for Event.ENTER_FRAME to Update Screen

For a recent project, I built a Flash asseessment engine as a plug-and-play tool for a client who wanted a simple way to build LMS ready assessments. The assessment engine loads an XML file and graphics to create custom assessments.

During development, I experienced a problem with the display of the dynamically loaded graphics. If a question had a graphic associated with it, the assessment engine;

  1. loaded the graphic,
  2. unloaded the previous graphic from the movie clip that holds graphics,
  3. placed the graphic in the movie clip,
  4. positioned the movie clip,
  5. sized and positioned a border around the graphic, and
  6. set the movie clip and border to be visible.

When the movie clip was set to be visible the previous picture with the previous position and border size flickered on stage before showing the correct display.

Once I had determined the code was being executed properly, I read more about the screen update process and discovered the importance of scheduling screen updates to happen with Event.ENTER_FRAME when using code to create displays or animate.

Event.ENTER_FRAME is dispatched at regular intervals determined by the frame rate. The key to solving the problem is understanding that when Event.ENTER_FRAME is dispatched, code is executed first, then the screen is rendered.

I added one step to the process (step 6). With the new code, if a question has a graphic associated with it, the assessment engine;

  1. loads the graphic,
  2. unloads the previous graphic from the movie clip that holds graphics,
  3. places the graphic in the moviclip,
  4. positions the movie clip,
  5. sizes and positions a border around the graphic,
  6. waits for a screen update, and
  7. sets the movie clip and border to be visible.

Steps 1-5 happen during the first Event.ENTER_FRAME dispatch. After Step 5 executes, the screen updates and the display is  set to the correct state. On the next Event.ENTER_FRAME, it is safe to execute the code that makes the display visible.

Below, I’ve place the code you need to implement a scheduled screen update.

// The listener is attached in the image load callback function
_image.addEventListener(Event.ENTER_FRAME, fShowImage);

// Gets called when the screen updates because that is when it is ok to make the image visible
  public static function fShowImage(e:Event):void
  {
   _image.removeEventListener(Event.ENTER_FRAME, fShowImage);
   Globals.Swf.border_mc.visible = Globals.Swf.graphic_mc.visible = true;
  }

Leave a Reply