[转]从写类笔记-描边文字

[转]自写类笔记-描边文字
http://uh.9ria.com/space-12147-do-blog-id-374.html

package{
 import flash.display.Bitmap;
 import flash.display.BitmapData;
 import flash.geom.Rectangle;
 import flash.text.TextField;
 import flash.text.TextFormat;

 public class BoundLabel extends Bitmap
 {
  private var _text:String="";
  private var _textField:TextField;
  public var defaultTextFormat:TextFormat=new TextFormat();
  public function BoundLabel(){
   super();
  }
  public function get text():String{
   return _text;
  }
  public function set text(value:String):void{
   if (_text==value) return;
   _text=value;
   _draw();
  }
  public function setTextFormat(format:TextFormat,beginIndex:int=-1,endIndex:int=-1):void{
   if (endIndex==-1){
    endIndex=_textField.text.length;
   }
   _textField.setTextFormat(format,beginIndex,endIndex);
   _parseText();
  }
  public function setBound(color:uint,beginIndex:int=-1,endIndex:int=-1):void{
   _addBound(color,beginIndex,endIndex);
  }
  private function _parseText():void{
   var _bitmapData:BitmapData;
   _textField.width=_textField.textWidth+5;
   _textField.height=_textField.textHeight+5;
   
   _bitmapData=new BitmapData(_textField.width,_textField.height,true,0);
   _bitmapData.draw(_textField);
   
   if (bitmapData) bitmapData.dispose();
   bitmapData=_bitmapData;
  }
  private function _draw():void{
   _textField=new TextField();
   _textField.defaultTextFormat=defaultTextFormat;
   _textField.text=_text;
   _parseText();
  }
  private function _trySetPixel32(toBitmapData_:BitmapData,i_:int,j_:int,color_:uint):void{
   if (i_>=0 && j_>=0 && i_<toBitmapData_.width && j_<toBitmapData_.height && toBitmapData_.getPixel32(i_,j_)==0){
    toBitmapData_.setPixel32(i_,j_,color_);
   }
  }
  private function _addBound(color:uint,beginIndex:int=-1,endIndex:int=-1):void{
   if (!bitmapData || color==0) return;
   
   var _rect:Rectangle=new Rectangle();
   if (beginIndex==-1) beginIndex=0;
   if (endIndex==-1) endIndex=_textField.text.length;
   for (var _i:int=beginIndex;_i<endIndex;_i++){
    _rect=_rect.union(_textField.getCharBoundaries(_i));
   }
   
   var _newBitmapData:BitmapData=new BitmapData(bitmapData.width,bitmapData.height,true,0);
   for (_i=0;_i<bitmapData.width;_i++){
    for (var _j:int=0;_j<bitmapData.height;_j++){
     if (bitmapData.getPixel32(_i,_j)!=0) {
      _newBitmapData.setPixel32(_i,_j,bitmapData.getPixel32(_i,_j));
      
      if (_rect.contains(_i,_j)){
       _trySetPixel32(_newBitmapData,_i-1,_j,color);
       _trySetPixel32(_newBitmapData,_i+1,_j,color);
       _trySetPixel32(_newBitmapData,_i,_j-1,color);
       _trySetPixel32(_newBitmapData,_i,_j+1,color);
      }
     }
    } 
   }
   bitmapData.dispose();
   bitmapData=_newBitmapData;
  }
 }
}


//setBound会被任何一种其他的操作覆盖,要最后执行。