Hi there,
I am trying to build a chatbox with some effects when there are more than a number of lines (e.g 6). Once there are more than 6 lines, the oldest message will fade away and all the messages will shift up when the faded message is disposed and removed from screen.
I am displaying the chat messages as Bitmaps and the animation is done using Tweener. Attached is the working example. And here are the codes:
public class TestChatBox extends Sprite
{
private var chatBitmaps:Array;
private var chatMessageContainer:MovieClip;
public function TestChatBox()
{
chatBitmaps = new Array();
chatMessageContainer = new MovieClip();
chatBox.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDownHandler);
addChild(chatMessageContainer);
showTotalMemory();
}
private function onKeyDownHandler(e:KeyboardEvent):void
{
var keyCode:int = e.keyCode;
var chatBox:ChatBox = e.currentTarget as ChatBox;
if (keyCode == Keyboard.ENTER) {
if (chatBox.getInput().length > 0) {
showChatMessage(chatBox.getInput());
chatBox.clearInput();
} else {
debug("Please enter a message");
}
}
}
private function debug(msg:String):void {
debug_txt.htmlText += msg;
debug_txt.scrollV = debug_txt.maxScrollV;
}
private function showChatMessage(msg:String):void {
var chatMessage:ChatMessage = new ChatMessage();
var bitmap:Bitmap;
var bitmapData:BitmapData;
chatMessage.setMessage(msg);
bitmapData = new BitmapData(chatMessage.width, chatMessage.height);
bitmapData.draw(chatMessage);
bitmap = new Bitmap(bitmapData);
chatBitmaps.push(bitmap);
chatMessageContainer.addChild(bitmap);
positionMessages();
bitmapData = null;
bitmap = null;
if (chatBitmaps.length > 6) {
clearOldMessage(chatBitmaps.shift());
debug("<i>Clearing oldest message...</i>");
}
}
private function clearOldMessage(chatBitmap:Bitmap):void {
Tweener.addTween(chatBitmap, {alpha:0, transition:"linear", time:1, onComplete:onTweenCompleted, onCompleteParams:[chatBitmap] } );
}
private function onTweenCompleted(chatBitmap:Bitmap):void
{
debug("<b>Oldest message cleared!</b>");
Tweener.removeTweens(chatBitmap);
chatMessageContainer.removeChild(chatBitmap);
chatBitmap = null;
positionMessages();
showTotalMemory();
}
private function showTotalMemory():void {
mem_txt.text = "System.totalMemory " + (System.totalMemory / 1024 / 1024) + " MB";
}
private function positionMessages():void {
for (var i:int = 0; i < chatBitmaps.length; i++) {
var chatBitmap:Bitmap;
var prevchatBitmap:Bitmap;
chatBitmap = chatBitmaps* as Bitmap;
if (i > 0)
prevchatBitmap = chatBitmaps[i - 1] as Bitmap;
if (prevchatBitmap != null)
chatBitmap.y = prevchatBitmap.y + prevchatBitmap.height;
else
chatBitmap.y = 0;
}
chatMessageContainer.x = chatBox.x;
chatMessageContainer.y = chatBox.y - chatMessageContainer.height;
}
}
Am I not disposing something correctly? :-/