AS3 形状的动态调整大小,最好的代码?

Dynamic resize of an AS3 Shape, best code?

我目前正在寻找有关在 AS3 中绘制流畅的圆角矩形的最佳实践的建议。我使用 Flash 已经有一段时间了,但现在正在寻求改进我的使用方式,并且有一些事情对于正在做的事情来说似乎过于复杂。

我有一个工作区屏幕,它是 1000px x 500px。

我为我的形状设置了一个 10px x 10px 边框间隙,如下所示设置它,使其具有圆角边缘, 25 像素。

一切正常,我可以调整屏幕大小,它始终允许 10 x 10 像素边框并保持 25 像素圆边,似乎所有调整大小的代码都太多了?有没有我不知道的更好的方法?

//Declare my Shape. 
public var my_shape : Shape = new Shape();

//In code call function to drawShape
drawBackgroundShape();

//I detect for screen resize.
stage.addEventListener( Event.RESIZE, resizeBackground );

public function drawBackgroundShape(): void {
    my_shape.graphics.lineStyle(1, 0xCCCCCC, 1);
    my_shape.graphics.beginFill(0xFFFFFF,1); 
    my_shape.graphics.drawRoundRect(10, 10, 980, 480, 25);
    my_shape.graphics.endFill();
    addChild(my_shape);
}

private function resizeBackground ( event:Event ):void {
    my_shape.graphics.clear();
    my_shape.graphics.lineStyle(1, 0xCCCCCC, 1);
    my_shape.graphics.beginFill(0xFFFFFF,1); 
    my_shape.graphics.drawRoundRect(10, 10, stage.stageWidth - 20, stage.stageHeight - 20, 25);
    my_shape.graphics.endFill();
}

这是更改正在绘制的形状大小的最有效方法吗?

提前致谢。

代码不是很好,因为

  1. 有一堆重复的代码
  2. 有些神奇的数字并不是真正必要的
  3. 封装的不是很好

您通过为边框创建 class 来解决问题 3。 1.通过只绘制一次边框的代码解决。最后 2. 通过重复使用该代码甚至用于初始化来解决。

package
{
    import flash.display.Shape;
    import flash.events.Event;

    public class BackgroundShape extends Shape
    {
        private var margin:Number;
        private var fillColor:uint;
        private var lineColor:uint;   

        public function BackgroundShape(margin:Number = 10, lineColor:uint = 0xCCCCCC, fillColor:uint = 0xFFFFFF)
        {
            this.margin = margin;
            this.lineColor = lineColor;
            this.fillColor = fillColor;

            addEventListener(Event.ADDED_TO_STAGE, onStage);
        }

        private function onStage(event:Event):void 
        {
            removeEventListener(Event.ADDED_TO_STAGE, onStage);

            stage.addEventListener(Event.RESIZE, drawBackground);

            drawBackground();
        }

        private function drawBackground(event:Event = null):void 
        {
            graphics.clear();
            graphics.lineStyle(1, lineColor, 1);
            graphics.beginFill(fillColor,1); 
            graphics.drawRoundRect(margin, margin, stage.stageWidth - 2 * margin, stage.stageHeight - 2 * margin, 25);
            graphics.endFill();
        }
    }
}

这允许您像使用任何其他 DisplayObject 一样使用 class。不必通过调用一些初始化函数将其添加到屏幕来区别对待它。没有必须为其他屏幕尺寸采用的硬编码幻数:

var bg:BackgroundShape = new BackgroundShape();
addChild(bg);