What is the best way to render to a UIComponent
which hasn't been added to the stage? (I'm using UIComponents as renderers for objects, and want to render new copies for image export, filtering, etc.)
Two strategies I've seen/used so far include realizing the component to ensure it calls all the lifecycle methods:
Add the component to
Application.application
, render with BitmapData.draw(), remove component. This is similar to what I've seen done for printing unrealized components as well.Add the component to a pop up window, render with BitmapData.draw(), dismiss popup after rendering complete.
I believe both of these just rely on the UI not refreshing while the current thread/event is executing, though (1) could also rely on the component being realized out of view.
Is there a better way?
What I've used in the past with much success is the following:
I've used this to snapshot various Flex charting components for use in PDF's generated on the server side. After getting the BitmapData I use the PNGEncoder or JPEGEncoder classes to compress the data, then encode it in Base64 before uploading to the server.
You can call the lifecycle function manually before using the BitmapData.draw(). Do the following.
The first 2 steps are not 100% necessary, you can put all codes into updateDisplayList(). Because you invoke the function manually, you don't have to worry this is invoked by Flex framework many times.
So much of a
UIComponent
's layout can be tied to it's context. This is especially true for a lot of its derivatives (e.g. HBox) since the fluidity of the layout is tied to it's parent's size and the number of siblings sharing its parents space.Additionally Flex can be a real pain to get to visually update. Often critical render functions aren't done synchronously ... there are
callLater
,callLater2
and other hacky approaches that make dealing with the auto-magical layout properties ofUIComponents
a major headache. Not even callingvalidateNow
orupdateDisplayList
can guarantee that the layout will be correct on the current frame (instead of a few frames in the future).I suggest the best thing you can do is not use a UIComponent and try and use a Sprite or other.
Your approach to attach it but make it invisible (
alpha = 0
,mouseEnabled = false
,mouseChildren = false
) is decent. You should listen for theFlexEvent.CREATION_COMPLETE
callback before you are certain it is properly laid out. Then you canbitmapData.draw
it and then remove it from the stage. If you must use UIComponents then I know of no better way.I'm pretty sure you can use the draw() method in BitmapData without having your component on the DisplayList.
For example is use it when I need to modify images I load with the Loader Class. In the init handler I create a BitmapData instance and draw the Bitmap from the loadInfo.content property, then copyPixels() or whatever I need to modify the loaded image