GetTextWidth bug when string contains "&"
Posted: Wed Dec 07, 2005 1:17 pm
For strings containing an ampersand (the "&" character), the GetTextWidth function returns a size that is too small - as you can see in the following simple ASP example, this is true.
It happens because the "&" character in the windows API subroutine interprets "&" as meaning "underline the next character", which is used to display keyboard shortcuts in menus and dialogs.
To work around this problem, simply replace "&" with "&&" in your string when getting the text width, e.g.:
W = Pic.GetTextWidth(Replace(Text,"&","&&"))
The "&&" combination is interpreted by the windows subroutine as "an actual & character", and will give the correct resulting width.
Code: Select all
<%
Const AX_GIF = 2
Const AX_To8Colors = 8
Const AX_NoDither = 0
Const AX_ToColors = 0
BG = RGB(255,255,255)
FG = RGB(255,0,0)
Text = "High & Low"
Set Pic = Server.CreateObject("GflAx.GflAx")
Pic.EnableLZW = True
Pic.FontName = "Verdana"
Pic.FontSize = 36
W = Pic.GetTextWidth(Text)
H = Pic.GetTextHeight(Text)
Pic.NewBitmap W, H, BG
Pic.TextOut Text, 0, 0, FG
Pic.SaveFormat = AX_GIF
Pic.ChangeColorDepth AX_To8Colors, AX_NoDither, AX_ToColors
Pic.SaveBitmap Server.MapPath("test.gif")
%>
<HTML><HEAD></HEAD><BODY BGCOLOR=#000000><IMG SRC="test.gif"></BODY></HTML>
To work around this problem, simply replace "&" with "&&" in your string when getting the text width, e.g.:
W = Pic.GetTextWidth(Replace(Text,"&","&&"))
The "&&" combination is interpreted by the windows subroutine as "an actual & character", and will give the correct resulting width.