绘制动态图形,然后用颜色填充(AS3)

时间:2014-04-24 08:43:07

标签: actionscript-3 flash dynamic colors shapes

我想使用仅限Flash AS3制作一个饼图。我制作了一个绘制分段圆圈的代码,所以我可以使用它们来表示不同的部分。

我的问题: 我确实有代码可以创建尽可能多的馅饼,但是我需要一个代码来填充不同的颜色。 (使段1蓝色,段2红色等)

我的代码如下:

/**
 * Draw a segment of a circle
 * @param target    <Sprite> The object we want to draw into
 * @param x         <Number> The x-coordinate of the origin of the segment
 * @param y         <Number> The y-coordinate of the origin of the segment
 * @param r         <Number> The radius of the segment
 * @param aStart    <Number> The starting angle (degrees) of the segment (0 = East)
 * @param aEnd      <Number> The ending angle (degrees) of the segment (0 = East)
 * @param step      <Number=1> The number of degrees between each point on the segment's circumference
 */
function drawSegment(target:Sprite, x:Number, y:Number, r:Number, aStart:Number, aEnd:Number, step:Number = 1):void {
        // More efficient to work in radians
        var degreesPerRadian:Number = Math.PI / 180;
        aStart *= degreesPerRadian;
        aEnd *= degreesPerRadian;
        step *= degreesPerRadian;

        // Draw the segment
        target.graphics.moveTo(x, y);
        for (var theta:Number = aStart; theta < aEnd; theta += Math.min(step, aEnd - theta)) {
            target.graphics.lineTo(x + r * Math.cos(theta), y + r * Math.sin(theta));
        }
        target.graphics.lineTo(x + r * Math.cos(aEnd), y + r * Math.sin(aEnd));
        target.graphics.lineTo(x, y);
};

graphics.lineStyle(2,0x000000)
drawSegment(this,100,100,100,0,130,3);
drawSegment(this,100,100,100,130,200,3);
drawSegment(this,100,100,100,200,360,3);

1 个答案:

答案 0 :(得分:1)

这很简单。您可以使用提供的颜色向beginFill()功能添加endFill()drawSegment次来电。当然,为此添加一个参数。

function drawSegment(target:Sprite, x:Number, y:Number, r:Number, aStart:Number, aEnd:Number, color:uint=0x0, step:Number = 1):void {
        // More efficient to work in radians
        var degreesPerRadian:Number = Math.PI / 180;
        aStart *= degreesPerRadian;
        aEnd *= degreesPerRadian;
        step *= degreesPerRadian;

        // Draw the segment
        target.graphics.beginFill(color,1); // second parameter is alpha
        target.graphics.moveTo(x, y);
        for (var theta:Number = aStart; theta < aEnd; theta += Math.min(step, aEnd - theta)) {
            target.graphics.lineTo(x + r * Math.cos(theta), y + r * Math.sin(theta));
        }
        target.graphics.lineTo(x + r * Math.cos(aEnd), y + r * Math.sin(aEnd));
        target.graphics.lineTo(x, y);
        target.graphics.endFill();
};

实际上,你最终应该从这个函数中创建一个“PieChart”类,这样它就会有一个共同的中心位置,半径,椭圆属性,线条样式,还有它自己的Shape来绘制on,而不是使用函数以某种方式绘制某个地方。说public class PieChart extends Sprite {...}并在this.graphics上绘图。