Tuesday, June 24, 2008

AS3 vertical gradient fills

The examples for gradient fills are either squares, or rectangles with the gradient going from left to right:
http://livedocs.adobe.com/flex/3/langref/flash/display/Graphics.html#beginGradientFill()

So, how do you make a horizontal rectangle, with a vertical linear gradient? Everything I've tried (i.e. rotating it 90 degrees) gives me a solid colour. Here is one failure example (270 degree rotation, then translated back the height).

s.graphics.beginGradientFill(GradientType.LINEAR,
[0x666666,0x666666],[0.9,0.1],[0,255],
new Matrix(0,-1,1,0,height,0));
s.graphics.drawRect(x,y,width,height);


(I'm actually giving up and will instead make this 9 pixel high gradient (a fancy drop shadow effect) by drawing 9 lines! But, please, somebody must have some sample code they can share?)

3 comments:

  1. Hey Darren,
    I think I've got a solution for you. All that you were missing is that third property inside of the matrix that specifies rotation by radians. I hope it's not so late that you've created that gradient line by line.

    var shape1:Shape = new Shape();
    var matrix:Matrix = new Matrix();
    matrix.createGradientBox(163, 24, (Math.PI/180)*90, 0, 00);
    var colors:Array = [ 0xffffff, 0x000000];
    var alphas:Array = [ 1.0, 1.0];
    var ratios:Array = [ 0, 255];
    shape1.graphics.lineStyle(2,0xa1b0b6);
    shape1.graphics.beginGradientFill(GradientType.LINEAR,colors, alphas, ratios, matrix);
    shape1.graphics.drawRect( 0.0, 0.0, 163, 24);
    shape1.graphics.endFill();
    addChild(shape1);

    ReplyDelete
  2. Thanks to you, Darren and thanks to Piston Honda too for help me to resolve this problem!

    Greetings.

    ReplyDelete
  3. Make sure you set your:

    SpreadMethod.REPEAT;

    And within your matrix set rotation to:
    matrix.createGradientBox( 4000, 200, (Math.PI / 180) * 90 , 0, 0 );

    ReplyDelete