Question

I was trying to get the width of the string, using XTextWidth() function, but for some reason the returned value is always bigger than the actual displayed length of string. In the following example, the value printed out is 196, while if I measure the width on-screen, it's somewhere around 168 pixels (the following is compilable and runnable example):

import Control.Concurrent
import qualified Graphics.X11.Xlib as X
import qualified Graphics.X11.Xlib.Types as Xt
import qualified Graphics.X11.Types as Xt

main = do
  display <- X.openDisplay ""
  let dflt = X.defaultScreen display
      border = X.blackPixel display dflt
      background = X.whitePixel display dflt
  rootw <- X.rootWindow display dflt
  win <- X.createSimpleWindow display rootw 0 0 500 300 1 border background
  X.mapWindow display win
  X.moveWindow display win 0 0

  updateScreen display win

updateScreen display win = do
  gc <- X.createGC display win
  bgcolor <- initColor display "white"
  fgcolor <- initColor display "black"
  X.setBackground display gc bgcolor
  X.setForeground display gc fgcolor

  font <- X.loadQueryFont display "-misc-fixed-*-*-*-*-14-*-*-*-*-*-*"
  let str = "Some reasonably long string."
      len = X.textWidth font str
  putStrLn $ show len
  X.drawImageString display win gc 0 50 str

  X.freeFont display font
  X.freeGC display gc
  threadDelay 100000
  updateScreen display win

initColor :: X.Display -> String -> IO X.Pixel
initColor dpy color = do
  let colormap = X.defaultColormap dpy (X.defaultScreen dpy)
  (apros,_) <- X.allocNamedColor dpy colormap color
  return $ X.color_pixel apros

How can I fix it?

Was it helpful?

Solution

You are not displaying with the selected font. Try this:

X.setFont display gc $ X.fontFromFontStruct font
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top