在BitmapData上绘制样式文本

时间:2013-04-10 15:29:34

标签: flex air

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

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上绘制的文字字体和尺寸?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

在设置文本格式之前尝试设置text属性 - 并使用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;