您可以创建一个包含文本字段和背景的显示对象类。然后,您只需将事件侦听器添加到侦听任何更改的文本字段。每次发生更改时,背景都会将自身调整为文本字段的当前大小。
这是一个例子:
package
{
import flash.display.Bitmap;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLRequest;
import flash.text.TextFieldAutoSize;
import flash.text.TextFieldType;
import flash.text.TextFormat;
public class Main extends Sprite
{
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}// end function
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
loader.load(new URLRequest("images/koala.jpg"));
}// end function
private function onComplete(e:Event):void {
var bitmap:Bitmap = ((e.target as LoaderInfo).content as Bitmap);
var container:TextFieldContainer = new TextFieldContainer();
container.textField.autoSize = TextFieldAutoSize.LEFT;
container.textField.defaultTextFormat = new TextFormat(null, null, 0xFF0000);
container.textField.type = TextFieldType.INPUT;
container.textField.multiline = true;
container.setBackground(bitmap);
addChild(container);
}// end function
}// end class
}// end package
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.Event;
import flash.text.TextField;
class TextFieldContainer extends Sprite {
private var _textField:TextField;
private var _backgroundContainer:Sprite;
public function get textField():TextField {
return _textField;
}// end function
public function TextFieldContainer():void {
_backgroundContainer = new Sprite();
addChild(_backgroundContainer);
_textField = new TextField();
_textField.addEventListener(Event.CHANGE, onChange);
addChild(_textField);
}// end function
private function onChange(e:Event):void {
resizeBackground();
}// end function
public function setBackground(displayObject:DisplayObject):void {
if (_backgroundContainer.numChildren > 0) {
_backgroundContainer.removeChildAt(0);
}// end if
_backgroundContainer.addChild(displayObject);
resizeBackground();
}// end function
private function resizeBackground():void {
_backgroundContainer.width = _textField.width;
_backgroundContainer.height = _textField.height;
}
}// end function