package { import flash.display.BitmapData; import flash.display.GradientType; import flash.display.Shader; import flash.display.Shape; import flash.display.Sprite; import flash.events.Event; import flash.geom.Matrix; [SWF(width=300, height=300, backgroundColor=0x000000)] /** * Demonstrates how a shader could be used for custom fills or strokes in shapes * by loading a shader that draws a square gradient based on a gradient image * passed to the shader for colors. */ public class graphic_flex_image_effects_05_Flex_SquareGradientTest extends Sprite { protected var _shaderProxy:graphic_flex_image_effects_05_Flex_ShaderProxy; /** * Constructor. This sets up loading of shader, or applies shader if bytes have been embedded. */ public function graphic_flex_image_effects_05_Flex_SquareGradientTest() { _shaderProxy = new graphic_flex_image_effects_05_Flex_ShaderProxy("graphic-flex-image-effects-05-assets-squareGradient.pbj"); if (_shaderProxy.shader == null) { _shaderProxy.addEventListener(Event.COMPLETE, onShaderLoaded); } else { drawShader(); } } /** * Draws the custom gradient with the shader. */ protected function drawShader():void { var width:Number = stage.stageWidth; var height:Number = stage.stageHeight; // center the gradient on the stage _shaderProxy.center = [width/2, height/2]; // passes a gradient in a bitmap to the shader _shaderProxy.gradient = getGradient(); graphics.beginShaderFill(_shaderProxy.shader); graphics.drawRect(0, 0, width, height); graphics.endFill(); } /** * Draws a linear gradient into a shape, then captures its bitmap data. * * @return Bitmap data with a horizontal linear gradient drawn into it. */ protected function getGradient():BitmapData { // all the values for the gradient var colors:Array = [0xFF0000, 0xFF00FF, 0x0000FF, 0x00FFFF, 0x00FF00, 0xFFFF00, 0xFF0000]; var alphas:Array = [1, 1, 1, 1, 1, 1, 1]; var ratios:Array = [0, 38, 84, 125, 171, 214, 255]; var matrix:Matrix = new Matrix(); // gradient will be 360px wide to display all the colors in a 360 degree range; // height is unimportant for retrieving the colors, so it is made 1px high matrix.createGradientBox(360, 1); var shape:Shape = new Shape(); shape.graphics.beginGradientFill(GradientType.LINEAR, colors, alphas, ratios, matrix); shape.graphics.drawRect(0, 0, 360, 1); shape.graphics.endFill(); // draws gradient into bitmap data var bitmapData:BitmapData = new BitmapData(360, 1); bitmapData.draw(shape); return bitmapData; } /** * Handler for when the shader loads. This simply calls drawShader(). * * @param event Event dispatched by ShaderProxy. */ private function onShaderLoaded(event:Event):void { drawShader(); } } }