在生成的Sprite对象as3上绘制文本

时间:2013-07-30 12:44:09

标签: actionscript-3

每个人,我只是一个初学者,我有疑问。我的程序的想法是,当用户点击一个按钮时,会生成一个圆圈,它应该计算每个额外的圆圈,它应该看起来像这样:

enter image description here

数字应该在中心,我应该能够将数字与数字一起移动这是我的代码:

add_s.addEventListener(MouseEvent.CLICK,new_sond);


function new_sond(event:MouseEvent):void
{
    var btn:Sprite = new Sprite();  
    btn.graphics.beginFill(0x00FF00, 1);
    btn.graphics.drawCircle(400, 300, 25);
    btn.graphics.endFill();
    this.addChild(btn);


}

//----------------------------Drag And Drop----------------------
this.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownH);
this.addEventListener(MouseEvent.MOUSE_UP, mouseUpH);

function mouseDownH(evt:MouseEvent):void {
    var object = evt.target;
    object.startDrag();
}

function mouseUpH(evt:MouseEvent):void {
    var obj = evt.target;
        obj.stopDrag();
} 

如果有人可以帮助我,我将非常感激。 如何将文本设置为圆圈中心的apear,我仍然可以使用文本移动它们

3 个答案:

答案 0 :(得分:3)

这是Vesper应该发布的答案:)

Sprite添加TextField个对象。由于TextFieldSprite的子项,因此它将移动Sprite。您需要做的就是将文本放在圆圈的中间位置:

function new_sond(event:MouseEvent):void
{
    var btn:Sprite = new Sprite();  
    btn.graphics.beginFill(0x00FF00, 1);
    btn.graphics.drawCircle(400, 300, 25);
    btn.graphics.endFill();
    var textField = new TextField();
    textField.text = "1";
    textField.width = textField.textWidth; // default width is 100
    textField.height = textField.textHeight;
    textField.x = (25 - textField.textWidth)/2; // center it horizontally
    textField.y = (25 - textField.textHeight)/2; // center it vertically
    btn.addChild(textField);
    this.addChild(btn);
}

注意,正如@Joeson Hwang所建议的那样,您可以使用Shape对象而不是Sprite来绘制圆圈。 ShapeSprite更轻量级。但是,由于Shape未展开DisplayObjectContainer,因此您无法像使用Shape那样将子对象添加到Sprite

@Joeson Hwang的回答建议将Shape和文本添加到Sprite。但这不会为您节省任何费用,所以只需将图形直接绘制到Sprite,就像现在一样。

答案 1 :(得分:0)

使用btn:Shape(节省大量系统资源)。然后将Shape和您的文本放入Sprite中。你也可以在另一个Sprite中添加一个Sprite。

答案 2 :(得分:0)

您还可以使用flash.text.engine包:

function new_sond(event:MouseEvent):void
{
    var btn:Sprite = new Sprite();  
    btn.graphics.beginFill(0x00FF00, 1);
    btn.graphics.drawCircle(cx, cy, cr);
    btn.graphics.endFill();

    // Font format
    var fontDescription:FontDescription = new FontDescription("Arial"); 
    var format:ElementFormat = new ElementFormat(fontDescription, 16, 0x000088);        

    // Display text
    var textElement:TextElement = new TextElement('1', format); 

    var textBlock:TextBlock = new TextBlock(); 
    textBlock.content = textElement; 

    // New display object containing text
    var textLine:TextLine = textBlock.createTextLine(null, 500); 

    // Centers the text inside the circle
    textLine.x = cx + (cr - textLine.width) / 2;
    textLine.y = cy + (cr - textLine.height) / 2;       

    // Add text into button
    btn.addChild(textLine);

    this.addChild(btn);
}

有关在Creating and displaying text

中创建文字ActionScript 3.0 Developer’s Guide的详细信息