Tuesday, November 5, 2024

Displaying Fractions Correctly

Im trying to create a function that will displays fractions in a textfield in the correct format, because 1/4 or 1/2 isnt being accepted by e-learning people as the correct way to display a fraction. So to do this dynamically, i just thought about creating a 3 line dynamic textfield on the fly, placing the numerator of the fraction on the first line, a dash on the second line and the denominator on the third line and then changing the lineSpacing of the textfield to squeeze it all together vertically, but of course, this is the only property of the TextFormat object that is missing and thus cannot be set dynamically, nor can you pass a negative integer as a value for the TextFormat.leading property unless you specify it using the leading attribute of the textformat html node and pass it to the htmlText property of a textfield(Thanks to Peter Hall)….

So ive created a movieclip method that will display a fraction correctly for you. This function creates one container movieclip, which inside contains two textfields and one movieclip, the first textfield contains the numerator, the second textfield contains the denominator and the movieclip contains a line between the numerator and the denominator drawn using the drawing api.

MovieClip.prototype.createFractionField=function(name,depth,x,y,numerator,denominator,lineSpacing)
{
&nbsp&nbsp var cnt=this.createEmptyMovieClip(name,depth,{_x:x,_y:y})
&nbsp&nbsp cnt.createTextField("numerator",1,0,0,0,0)
&nbsp&nbsp var numeratorF=cnt.numerator
&nbsp&nbsp var dash=cnt.createEmptyMovieClip("dash",2)
&nbsp&nbsp cnt.createTextField("denominator",3,0,0,0,0)
&nbsp&nbsp var denominatorF=cnt.denominator
&nbsp&nbsp numeratorF.autoSize=denominatorF.autoSize=true
&nbsp&nbsp numeratorF.text=numerator
&nbsp&nbsp denominatorF.text=denominator
&nbsp&nbsp var nw=numeratorF._width
&nbsp&nbsp var dw=denominatorF._width
&nbsp&nbsp var gw=(nw>=dw) ? nw : dw
&nbsp&nbsp var hw=gw/2
&nbsp&nbsp numeratorF._x=hw-(nw/2)
&nbsp&nbsp denominatorF._x=hw-(dw/2)
&nbsp&nbsp dash.lineStyle(0,0x000000)
&nbsp&nbsp dash.lineTo(gw,0)
&nbsp&nbsp dash._y=numeratorF._height+lineSpacing
&nbsp&nbsp denominatorF._y=dash._y+dash._height+lineSpacing
}

And you use it like this:

//display 1/10 correctly as a fraction for me
this.createFractionField("myFraction",1,0,0,1,10)

Guy Watson (or FlashGuru as he is also known) has been an active, well
recognized figure in the Flash community for over four years,
supporting the community with tutorials, source files, moderating the
Flashkit forums, and running his own Flash resource Web site,
FlashGuru’s MX 101. Guy was one of two developers who created the ever
popular, award winning zoom interface for Relevare and now runs his
own company, FlashGuru LTD, which builds Flash Games & Applications
for clients such as Comic Relief, Egg and Channel 4.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles