import flash.display.BitmapData; // 场景中摆个叫 img 的 mc 就 ok var oldBmp:BitmapData = new BitmapData(img._width, img._height); oldBmp.draw(img); var newBmp:BitmapData = mosaic(oldBmp, 12); var mc = createEmptyMovieClip("mc", 1); mc.attachBitmap(newBmp, getNextHightestDepth()); mc._x = img._width; function mosaic(bmp:BitmapData, stride:Number):BitmapData { var startTime = getTimer();
var newBmp:BitmapData = new BitmapData(bmp.width, bmp.height); var w = bmp.width / stride + 1; var h = bmp.height / stride + 1; var edgeW = bmp.width % stride; // 边缘不足 stride 的部分 var edgeH = bmp.height % stride; var centerW = (stride-1)/2; // 第一格的中心点 var centerH = centerY; // 第一格永远是方的 var tmpX, tmpY; // 循环中的真实像素位置, 前面 w, h 被除过了.. var blockW, blockH; // 马赛克的格子
var i = -1; while (++i < w) { tmpX = i * stride; if (i == w - 1){ blockW = edgeW; } else { blockW = stride; } centerW = (blockW - 1) / 2; var j = -1; while (++j < h) { tmpY = j * stride; if (i == h - 1){ blockH = edgeH; } else { blockH = stride; } centerH = (blockH - 1) / 2; var color = bmp.getPixel(tmpX + centerW, tmpY + centerH); var m = -1; while (++m < blockW) { var n = -1 while (++n < blockH) { newBmp.setPixel(tmpX + m, tmpY + n,color); } } }