The Canvas layout container. We all know it, we all love it. Lets us place our components wherever we like. Such a good sport.

But the one aspect I dislike about the Canvas container is the lack of a background gradient. Why should buttons have all the fun?

After reading through the source code for the Canvas container and Button control, I realized creating a Canvas with a background gradient would be pretty easy, so long as I was willing to tinker around with the drawing API.

Which I was.

So how did I do it? I extended the Canvas container in a new AS3 class, and overrode the updateDisplayList() method. That’s it.

The beauty of this is that it doesn’t mess with the layout of the child components in the container. It just makes the background a whole lot prettier.

Sample code for the GradientCanvas:

    import mx.containers.Canvas;
    import mx.styles.StyleManager;
    import mx.utils.ColorUtil;

    public class GradientCanvas extends Canvas
        override protected function updateDisplayList
            (w : Number, h : Number) : void
            super.updateDisplayList (w, h);

            // retrieves the user-defined styles
            var fillColors : Array = getStyle ("fillColors");
            var fillAlphas : Array = getStyle ("fillAlphas");
            var cornerRadius : Number = getStyle ("cornerRadius");

            // converts the fill colors to RGB color values
            StyleManager.getColorNames (fillColors);

            // ready to draw!
             graphics.clear ();

            // draws the gradient
            drawRoundRect (0, 0, w, h, cornerRadius, fillColors,
                fillAlphas, verticalGradientMatrix (0, 0, w, h));

You’ll notice in the code that I only check for the fillColors, fillAlphas and cornerRadius styles in my component. That’s all I really needed for my GradientCanvas container, but if you wanted to add support for borders and shadows you would simply add the styles and draw them as well.

Piece of pie.