In Flash CS4 AS3.0 how can I change a shapes fill colour with a click?
I'm building an activity for young kids where they click on a 开发者_JS百科colour in a palette (mouse cursor will be a paint brush) then click on various shapes that I'll layer to create a picture.
depending on the colour they select they should be able to fill the shapes with that colour. Change colors half way through change their mind etc.
I have no issues using an earlier AS version if its easier.
you can use flash.filters.ColorMatrixFilter - there are examples in the linked documentation.
it's also very easy to do this using Tweener's ColorShortcuts by assigning the _Color
property a hexidecimal color value. this method additionally lets you very easily fade in the color by optionally assigning a non-zero value to the required time
property.
Tweener.addTween(myShape, {time: 0.0, _Color: 0xFF0000});
keep in mind that any bitmap filters, like drop shadows, or any children of your shape (if it's a sprite) will also change color. although it's just as easy to separate each element of your shape by using a container.
[EDIT] rather than using Tweener, as i hastily suggested earlier, or the rather complicated ColorMatrixFilter, you can use a ColorTransform object to easily change the color of a display object. this is also the most common approach in AS3. here's an example:
import flash.geom.ColorTransform;
var myShape:Shape = new Shape();
myShape.graphics.beginFill(0xFF0000, 1.0);
myShape.graphics.drawRect(0, 0, 100, 100);
myShape.graphics.endFill();
addChild(myShape);
var myColorTransform:ColorTransform = new ColorTransform;
myColorTransform.color = 0x0000FF;
myShape.transform.colorTransform = myColorTransform;
the above code draws a red rect, adds it to the stage and then uses a ColorTransform object to change its color to blue.
I must warn you that getting this to work the same way that say Paint works will be actually pretty difficult.
I'd look at making your entire canvas a Bitmap
.
Resources:
Bitmap
BitmapData
(this one will have the key methods)
When shapes are drawn and whatnot, use the fillRect()
method. For a tool like a paint bucket (like in paint), take a look at the floodFill()
method.
I'm not really sure how could could create a paint bucket tool, but my mind is thinking along the lines of having a loop that uses getPixel()
to check out the colours of each of the pixels surrounding where you click, and then uses setPixel()
to change the colour of each. You'll have to create a method that returns an array of all the pixels that are of a certain colour and not blocked off by another colour (ie so you don't use the paint bucket and change the colour of all the pixels on the canvas).
There's likely libraries out there for this sort of stuff too.
Hope this gets you on the right track.
Or just use a filter. See DisplayObject.filters
精彩评论