Flash教程:互动的橡皮刷
只要在一张图片上用draw画一个透明度为零的图片,就可以实现在draw的区域图片透明了。
完成效果如下:
点击选择右边的橡皮刷或者画笔图标,再用鼠标在画面上拖动,看看会出现什么情况?
AS代码如下:
//导入所需要的类
import flash.display.BitmapData;
import flash.geom.Rectangle;
import flash.geom.Point;
//初始点(0,0)
var base_point:Point = new Point(0, 0);
//初始区域(0,0,25,25)
var base_rectangle:Rectangle = new Rectangle(0, 0, 25, 25);
//导入库中图片
var bit1:BitmapData = BitmapData.loadBitmap("img1");
//定义org_bit:BitmapData用于恢复图片
var org_bit:BitmapData = new BitmapData(mc._width, bit1.height, true, 0);
org_bit.draw(bit1);
//draw_bit拷贝org_bit用于涂鸦操作
var draw_bit:BitmapData = org_bit.clone();
//导入到舞台中
_root.createEmptyMovieClip("draw_mc", 1);
draw_mc.attachBitmap(draw_bit, 1);
//定义橡皮刷erase_bit和笔刷redraw_bit argb为0(透明)
var erase_bit:BitmapData = new BitmapData(mc1._width, mc1._height, true, 0);
var redraw_bit:BitmapData = erase_bit.clone();
//橡皮刷erase_bit填充为白色,这里注意a必须不为0 rbg为FFFFFF
erase_bit.fillRect(erase_bit.rectangle, 0xFFFFFFFF);
//定义橡皮刷erase_bit和笔刷redraw_bit形状 注意mc1必须为黑色 你也可以尝试用别的颜色看看效果慢慢体会吧
erase_bit.draw(mc1);
redraw_bit.draw(mc1);
//交换erase_bit r通道和a通道数值 所以a通道数值为00
erase_bit.copyChannel(erase_bit, erase_bit.rectangle, new Point(0, 0), 1, 8);
//保存当前使用的工具
var tools:String;
//点击笔刷工具
mc_bursh.onRelease = function()
{
this.gotoAndStop(2);
mc_earse.gotoAndStop(1);
tools = "bursh";
};
//点击橡皮刷工具
mc_earse.onRelease = function()
{
this.gotoAndStop(2);
mc_bursh.gotoAndStop(1);
tools = "easre";
};
//在draw_bit上涂鸦
draw_mc.onPress = function()
{
trace(tools);
if (tools == "bursh")
{
this.onMouseMove = bursh_pic;
}
if (tools == "easre")
{
this.onMouseMove = earse_pic;
}
};
//停止涂鸦
draw_mc.onRelease = function()
{
delete this.onMouseMove;
};
//橡皮刷工具
function earse_pic()
{
var now_rect:Rectangle = new Rectangle(_xmouse, _ymouse, _xmouse base_rectangle.width, _ymouse base_rectangle.height);
trace(now_rect);
//在draw_bit上使用copyPixels alpha为false 透明区域透明 不透明区域保持原色
draw_bit.copyPixels(draw_bit, now_rect, new Point(_xmouse, _ymouse), erase_bit, new Point(0, 0), false);
updateAfterEvent();
}
//笔刷工具
function bursh_pic()
{
var now_rect:Rectangle = new Rectangle(_xmouse, _ymouse, _xmouse base_rectangle.width, _ymouse base_rectangle.height);
trace(now_rect);
//在org_bit上使用copyPixels alpha为true 则笔刷工具只有不透明的地方起作用
draw_bit.copyPixels(org_bit, now_rect, new Point(_xmouse, _ymouse), redraw_bit, new Point(0, 0), true);
updateAfterEvent();
}
//移动背景图观察效果
mc.onPress = function()
{
this.startDrag();
};
mc.onRelease = function()
{
this.stopDrag();
};