Autosize text to fit the width of a button

风格不统一 提交于 2020-01-24 01:18:09

问题


I've had a good look around but couldn't find anything that directly solves my problem. There are several posts which are along the right lines, but I can't get my head around it in order to fix the issue.

I need to automatically resize the text so that it doesn't exceed the width of the button. The maximum length for my sized text appears to be 13 characters before it will become too large.

--

The program starts by dynamically creating several buttons, filling them with the title and description as set in an XML document.

To add the text I have this code:

var tform:TextFormat = new TextFormat();
tform.size = 20;
tform.font = "Arial";
tform.align = TextFormatAlign.CENTER;
tform.color = 0xFFFFFF;
tform.bold = true;

var tfield:TextField = new TextField();
tfield.text = texttitle;
tfield.width = button.width;
tfield.x = 0;
tfield.y = 30;

tfield.setTextFormat(tform);
addChild(tfield);

This positions the text directly in the centre of the button 30 pixels from the top. The problem I therefore face is how to modify the font size in order to keep the text within the box.

--

Now, because I set the width to the the size of the panel, I can't see any obvious way of looping through to set the font size according to the maximum allowed width.

I trust this all makes sense, and I welcome any modifications to make the code more efficient as I'm relatively new to AS3 and Flash and therefore am still on the learning curve.

Regards, Jon.


回答1:


I've ran across this problem and solved it by looping over the text setting until it fits

something along the lines of this

while (tf.textwidth > button.width){
   myTextFormat.size = myTextFormat.size - 1;
   tf.setTextFormat(myTextFormat);
   tf.autoSize = "left";
}


来源:https://stackoverflow.com/questions/10076442/autosize-text-to-fit-the-width-of-a-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!