Majid Laissi
Majid Laissi

Reputation: 19788

Change color of a Circle

I have the following class, that represents a red circle:

public class AElement extends UIComponent {

    public var radius:int;

    override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
        graphics.beginFill(0xFF0000);
        graphics.drawCircle(x, y, radius);
        graphics.endFill();
    }

}

I would like to add a method that changes the color of the circle, so I came up with this solution:

    public function updateColor(color:uint):void {
        graphics.beginFill(color);
        graphics.drawCircle(x, y, radius);
        graphics.endFill();
    }

It works, but I believe this only draws another circle on top of the first one.

Is there any way to change the first circle's color instead of drawing another one ?

Upvotes: 0

Views: 716

Answers (1)

user1901867
user1901867

Reputation:

Just call .clear() before you start drawing

public function updateColor(color:uint):void {
    graphics.clear();
    graphics.beginFill(color);
    graphics.drawCircle(x, y, radius);
    graphics.endFill();
}

then you can redraw in a new colour.

Edit:

To change the colour of an object you can use ColorTransform:

myDisplayObject.transform.colorTransform = new ColorTransform(0, 0, 0, 0, r, g, b, a);

Where r,g and b are the red,green and blue parts of the colour, and a is the alpha value (all between 0-255). eg:

public function updateColor(color:uint):void {
    var a:int = (color&0xFF000000)>>24;
    var r:int = (color&0x00FF0000)>>16;
    var g:int = (color&0x0000FF00)>>8;
    var b:int = (color&0x000000FF);
    this.transform.colorTransform = new ColorTransform(0, 0, 0, 0, r, g, b, a);
}

or for colours without alpha:

public function updateColor(color:uint):void {
    var r:int = (color&0xFF0000)>>16;
    var g:int = (color&0x00FF00)>>8;
    var b:int = (color&0x0000FF);
    this.transform.colorTransform = new ColorTransform(0, 0, 0, 0, r, g, b, 255);
}

However, this affects the whole display object and any children - not just whatever is drawn to graphics. So, assuming your class contains other visual objects, you'd be better sticking with the clear() option (imho).

Upvotes: 3

Related Questions