Actionscript 3: how to clear just a portion of a Graphics object
I am making a Flash CS5 application in which the user draws transparent overlays on a Sprite placed on top of an image. The user needs开发者_JAVA百科 to be able to erase his input as in MS Paint, Adobe Photoshop, or GIMP. Because the Sprite is on top of an image, there is no safe clear color I can think of to draw over the section that the user has just rubbed his eraser over.
How can I perform or simulate a partial clear of a Graphics object?
Does it actually need to be a Sprite, as in vector graphics? Could the overlay be a Bitmap object? And do you want to make pixel level color changes, like the paint brush or the eraser does in MS Paint?
If you really don't need vector graphics I suggest you use a Bitmap object instead. Follow these steps:
the Sprite overlay is actually a Bitmap overlay, be sure to make it transparent
var bmp : Bitmap = new Bitmap( new BitmapData(imgWidth, imgHeight, true, 0));
you create vector graphics in a temp Sprite or event better a Shape because you don't need containment.
var tmpVectorGraphics : Shape = new Shape();
// draw whatever you want using the graphics library functions
drawStuffInShape(tmpVectorGraphics);
now draw the vector graphics content on the bitmapdata of the Bitmap object - transforming the vectorgraphics in bitmap graphics
bmp.bitmapData.draw(tmpVectorGraphics);
// if what you've drawn in the shape containing the vector graphics is overlayed
// the same way as the bmp object, you don't need to specify a matrix object
after this you can clear the tmpVectorGraphics
tmpVectorGraphics.graphics.clear();
to clear pixels like the eraser does in Paint, you can create a transparent shape and copy it to specific positions in the bitmap.
// create the eraser bitmap data
var eraser : BitmapData = new BitmapData(5, 5, true, 0);
// this is the location of where you want the eraser to be applied
var pos : Point = new Point (locationX, locationY);
// apply the eraser to the main bmp overlay to a specific location
bmp.bitmapData.copyPixels(eraseer, eraser.rect, pos);
So anytime you want to add some graphics, you generate them in the tmpVectorGraphics Shape and then draw it on the Bitmap object. This is also faster in terms of performance because the more graphic commands you did to create the Shape the more expensive is for that to render per frame. The bitmap is cached in memory and it doesn't matter how complex the graphics are in it.
There is a lot of stuff you can do with BitmapData in actionscript and is very cheap in terms of processing speed so I suggest you search for some BitmapData tutorials because you can make an amazing paint application if you know how to master this class :)
Cheers, Mihnea
精彩评论