Resizing FLVPlayback Instance to Fit the Stage
As I had mentioned in one of my previous posts, I have used the FLVPlayback class for some of the video player projects I have worked on in the past. The newer version (2.5) supports some cool features such as Dynamic Streaming and DVR capabilities. There are some limitations, however, and one of them is the fact that you cannot give it a percentage value for its width or height so that it will scale with a SWF that is being resized. As such, you have to give it a specific width and height in absolute pixels. So how do you make sure it will always be the same size as your SWF?
The first thing I tried to do was manually set it to the width and height of the stage when I was creating the instance. In most of my Flex projects, I always use the creationComplete method in the Application tag to run all of my initialization code. From there, I call a private method that creates the FLVPlayback instance, sets its properties, and adds it to the stage. So I figured it would be easy to do something like (using video as my FLVPlayback instance name):
video.width = stage.stageWidth; video.height = stage.stageHeight; |
However, trying to run this code resulted in an error being thrown complaining that the stage reference was null. Null? How could it be null after the creationComplete has been fired? As it turns out, the stage isn’t actually created until something has been added to it. I ended up finding the following information (special thanks to Ans) that shed some light on the subject. It turns out that you need to listen for the Event.ADDED_TO_STAGE event like so:
video.addEventListener(Event.ADDED_TO_STAGE, videoAddedToStage); private function videoAddedToStage(e:Event):void { // Now stage should be a valid reference and we can set the width and height of our instance video.width = stage.stageWidth; video.height = stage.stageHeight; // Add an event listener for stage resize stage.addEventListener(Event.RESIZE, stageResize); } |
This will ensure that after your application loads, the FLVPlayback instance will be assigned the same width and height as the stage. If you want to make sure that it is ALWAYS the same width and height, you can listen for the Event.RESIZE event on the stage. Notice that I added the event listener in the other event listener… if you try to add an event listener to the stage when it is still null, you will obviously end up with another null reference error.
private function stageResize(e:Event):void { // Resize the FLVPlayback instance so it is the same width and height as the stage video.width = stage.stageWidth; video.height = stage.stageHeight; } |