2013-04-10 48 views
0

我有一个函数可以在BitmapData上绘制一个字符串。问题是,指定的TextFormat不会影响写在图像上的文本。我用文本格式指定的大小,字体完全没有使用。在BitmapData上绘制样式文本

function drawString(target:BitmapData,text:String,color:uint,x:Number,y:Number):void { 
     var channelName:TextField = new TextField(); 

     channelName.textColor=color; 
     channelName.antiAliasType = AntiAliasType.ADVANCED; 
     channelName.alpha=1.0; 

     var txtFormat:TextFormat = new TextFormat("Verdana",25,color,true); 
     txtFormat.size=Number(25); 
     txtFormat.font="Verdana"; 
     txtFormat.bold=true; 
     channelName.setTextFormat(txtFormat); 
     channelName.text = text; 

     channelName.defaultTextFormat = txtFormat; 
     channelName.cacheAsBitmap = true; 
     channelName.width=400; 

     var mat:Matrix = new Matrix(); 
     mat.translate(x,y); 
     target.draw(channelName,mat); 

    } 

如何自定义通过BitmapData绘制的文本字体和大小?

+1

尝试在设置文本格式之前设置文本属性 - 并使用setTextFormat(...)或defaultTextFormat = ...不是两个 – 2013-04-10 16:17:46

+0

@LeeBurrows工作。请添加一个答案被接受 – deadlock 2013-04-10 18:02:34

回答

0

尝试设置文本格式之前设置文本属性 - ,要么使用调用setTextFormat(...)或defaultTextFormat =。 ..不都

你也可以删除这些行:

//does the same thing as new TextFormat("Verdana",25,color,true) 
txtFormat.size=Number(25); 
txtFormat.font="Verdana"; 
txtFormat.bold=true; 

//only useful if you add textField to the display list (ie: if you did addChild(channelName) 
channelName.cacheAsBitmap = true; 
1

这里是我的代码:

<?xml version="1.0" encoding="utf-8"?> 
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" 
        xmlns:s="library://ns.adobe.com/flex/spark" 
        xmlns:mx="library://ns.adobe.com/flex/mx" width="640" height="400" creationComplete="init(event)"> 
<fx:Script> 
    <![CDATA[ 
     import mx.events.FlexEvent; 

     [Embed(source='com/drawtext/Image.jpg')] 
     public var Picture:Class; 

     protected function init(event:FlexEvent):void 
     { 
      var bitmapData:BitmapData = new BitmapData(640, 400, true, 0xFF82DC); 
      bitmapData.draw(new Picture()); 
      img.source = bitmapData; 
      drawString(bitmapData, "It is Yours!", 0xff0000, 70, 60); 
     } 

     protected function drawString(target:BitmapData,text:String,color:uint,x:Number,y:Number):void 
     { 
      var channelName:TextField = new TextField(); 

      channelName.antiAliasType = AntiAliasType.ADVANCED; 

      var txtFormat:TextFormat = new TextFormat(); 
      txtFormat.size = 35; 
      txtFormat.font = "Verdana"; 
      txtFormat.bold = true; 

      channelName.defaultTextFormat = txtFormat; 

      channelName.width = 400; 
      channelName.height = 40; 
      channelName.textColor=color; 
      channelName.text = text; 

      var mat:Matrix = new Matrix(); 
      mat.translate(x, y); 

      target.draw(channelName, mat); 
     } 

    ]]> 
</fx:Script> 

<s:Image id="img" width="640" height="400"/> 
</s:WindowedApplication> 

结果:

enter image description here