Starling 环形进度条实现

项目初期想实现这个效果来着,查了很多资料(包括式神的<神奇的滤镜>),也没找到完美的实现方法,,当时时间紧迫,就找了传统的进度条来代替实现。

最近偶然心血来潮,查了各方面资料,终于找到实现的方法,效果图放上。

 

代码1:使用Starling-graphic-extension绘制多边形,用多边形的角度变化来模拟扇形的动画(原理很简单,创意不错),percentage表示进度(0-1)。 

private function drawPieMask (graphics:Graphics , percentage:Number , radius:Number = 50, x:Number = 0, y:Number = 0, rotation:Number = 0 , sides:int = 6) :void  {
    graphics .clear ();
    
    graphics .beginTextureFill (_testTex );
     // graphics should have its beginFill function already called by now
    graphics .moveTo (x , y );
     if (sides < 3 ) sides = 3; // 3 sides minimum
     // Increase the length of the radius to cover the whole target
    radius /= Math .cos (1 /sides * Math .PI );
     // Shortcut function
     var lineToRadians:Function = function (rads:Number ): void {
          graphics .lineTo (Math .cos (rads ) * radius + x , Math. sin( rads) * radius + y) ;
     };
     // Find how many sides we have to draw
     var sidesToDraw:int = Math .floor (percentage * sides );
     for ( var i:int = 0; i <= sidesToDraw; i ++)
          lineToRadians ((i / sides ) * (Math .PI * 2 ) + rotation) ;
     // Draw the last fractioned side
     if (percentage * sides != sidesToDraw )
          lineToRadians (percentage * (Math .PI * 2 ) + rotation) ;
    graphics .lineTo (x ,y );
    
    graphics .endFill ();
}   

参见 http://flassari.is/2009/11/pie-mask-in-as3/,附上原理swf(没看到的请刷新页面)

 

代码2:基础纹理的生成(可以使用图片或者动态合成)

var bmp:BitmapData = new BitmapData(256, 256, true, 0x0); //纹理的非绘制部分alpha为0
var sprite:Sprite = new Sprite();
sprite.graphics.beginFill(ColorUtil.YELLOW);
sprite.graphics.drawCircle(50, 50, 50);
bmp.draw(sprite);

_testTex = Texture.fromBitmapData(bmp, false);
var img:Image = new Image(_testTex);
img.x = 0;
img.y = 600;

var mask:Shape = new Shape();
mask.x = img.x;
mask.y = img.y;
container.addChild(mask);
mask.addEventListener(Event.ENTER_FRAME, function():void {
     drawPieMask(mask.graphics, _testProg, 50, 50, 50, -Math.PI/2, 3);
     _testProg = (_testProg + 0.01) % 1;
});     

var circle:Shape = new Shape();
circle.graphics.beginFill(ColorUtil.GREEN);
circle.graphics.drawCircle(0, 0, 40);
circle.x = img.x + 50;
circle.y = img.y + 50;
container.addChild(circle);

 

 

附:测试发现release版本在ios上会有问题,现象是只能转到一个角度,然后就消失了。原因在于starling.display.graphics.Fill的isReflex函数,在release版本会出现问题,只能画边数少于等于3的多边形,把这个调用注释掉就可以了。纯2d的游戏,无所谓顺时针逆时针,能画出来就好。至于为什么在ios的release版本上有问题,这个就不清楚了。桌面release版本没有发现这个问题。

 

源码下载

posted on 2013-09-03 16:55  非合格程序员  阅读(1458)  评论(4编辑  收藏  举报