grid.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. package gofpdf
  2. import (
  3. "math"
  4. "strconv"
  5. )
  6. func unused(args ...interface{}) {
  7. }
  8. // RGBType holds fields for red, green and blue color components (0..255)
  9. type RGBType struct {
  10. R, G, B int
  11. }
  12. // RGBAType holds fields for red, green and blue color components (0..255) and
  13. // an alpha transparency value (0..1)
  14. type RGBAType struct {
  15. R, G, B int
  16. Alpha float64
  17. }
  18. // StateType holds various commonly used drawing values for convenient
  19. // retrieval (StateGet()) and restore (Put) methods.
  20. type StateType struct {
  21. clrDraw, clrText, clrFill RGBType
  22. lineWd float64
  23. fontSize float64
  24. alpha float64
  25. blendStr string
  26. cellMargin float64
  27. }
  28. // StateGet returns a variable that contains common state values.
  29. func StateGet(pdf *Fpdf) (st StateType) {
  30. st.clrDraw.R, st.clrDraw.G, st.clrDraw.B = pdf.GetDrawColor()
  31. st.clrFill.R, st.clrFill.G, st.clrFill.B = pdf.GetFillColor()
  32. st.clrText.R, st.clrText.G, st.clrText.B = pdf.GetTextColor()
  33. st.lineWd = pdf.GetLineWidth()
  34. _, st.fontSize = pdf.GetFontSize()
  35. st.alpha, st.blendStr = pdf.GetAlpha()
  36. st.cellMargin = pdf.GetCellMargin()
  37. return
  38. }
  39. // Put sets the common state values contained in the state structure
  40. // specified by st.
  41. func (st StateType) Put(pdf *Fpdf) {
  42. pdf.SetDrawColor(st.clrDraw.R, st.clrDraw.G, st.clrDraw.B)
  43. pdf.SetFillColor(st.clrFill.R, st.clrFill.G, st.clrFill.B)
  44. pdf.SetTextColor(st.clrText.R, st.clrText.G, st.clrText.B)
  45. pdf.SetLineWidth(st.lineWd)
  46. pdf.SetFontUnitSize(st.fontSize)
  47. pdf.SetAlpha(st.alpha, st.blendStr)
  48. pdf.SetCellMargin(st.cellMargin)
  49. }
  50. // TickFormatFncType defines a callback for label drawing.
  51. type TickFormatFncType func(val float64, precision int) string
  52. // defaultFormatter returns the string form of val with precision decimal places.
  53. func defaultFormatter(val float64, precision int) string {
  54. return strconv.FormatFloat(val, 'f', precision, 64)
  55. }
  56. // GridType assists with the generation of graphs. It allows the application to
  57. // work with logical data coordinates rather than page coordinates and assists
  58. // with the drawing of a background grid.
  59. type GridType struct {
  60. // Chart coordinates in page units
  61. x, y, w, h float64
  62. // X, Y, Wd, Ht float64
  63. // Slopes and intercepts scale data points to graph coordinates linearly
  64. xm, xb, ym, yb float64
  65. // Tickmarks
  66. xTicks, yTicks []float64
  67. // Labels are inside of graph boundary
  68. XLabelIn, YLabelIn bool
  69. // Labels on X-axis should be rotated
  70. XLabelRotate bool
  71. // Formatters; use nil to eliminate labels
  72. XTickStr, YTickStr TickFormatFncType
  73. // Subdivisions between tickmarks
  74. XDiv, YDiv int
  75. // Formatting precision
  76. xPrecision, yPrecision int
  77. // Line and label colors
  78. ClrText, ClrMain, ClrSub RGBAType
  79. // Line thickness
  80. WdMain, WdSub float64
  81. // Label height in points
  82. TextSize float64
  83. }
  84. // linear returns the slope and y-intercept of the straight line joining the
  85. // two specified points. For scaling purposes, associate the arguments as
  86. // follows: x1: observed low value, y1: desired low value, x2: observed high
  87. // value, y2: desired high value.
  88. func linear(x1, y1, x2, y2 float64) (slope, intercept float64) {
  89. if x2 != x1 {
  90. slope = (y2 - y1) / (x2 - x1)
  91. intercept = y2 - x2*slope
  92. }
  93. return
  94. }
  95. // linearTickmark returns the slope and intercept that will linearly map data
  96. // values (the range of which is specified by the tickmark slice tm) to page
  97. // values (the range of which is specified by lo and hi).
  98. func linearTickmark(tm []float64, lo, hi float64) (slope, intercept float64) {
  99. ln := len(tm)
  100. if ln > 0 {
  101. slope, intercept = linear(tm[0], lo, tm[ln-1], hi)
  102. }
  103. return
  104. }
  105. // NewGrid returns a variable of type GridType that is initialized to draw on a
  106. // rectangle of width w and height h with the upper left corner positioned at
  107. // point (x, y). The coordinates are in page units, that is, the same as those
  108. // specified in New().
  109. //
  110. // The returned variable is initialized with a very simple default tickmark
  111. // layout that ranges from 0 to 1 in both axes. Prior to calling Grid(), the
  112. // application may establish a more suitable tickmark layout by calling the
  113. // methods TickmarksContainX() and TickmarksContainY(). These methods bound the
  114. // data range with appropriate boundaries and divisions. Alternatively, if the
  115. // exact extent and divisions of the tickmark layout are known, the methods
  116. // TickmarksExtentX() and TickmarksExtentY may be called instead.
  117. func NewGrid(x, y, w, h float64) (grid GridType) {
  118. grid.x = x
  119. grid.y = y
  120. grid.w = w
  121. grid.h = h
  122. grid.TextSize = 7 // Points
  123. grid.TickmarksExtentX(0, 1, 1)
  124. grid.TickmarksExtentY(0, 1, 1)
  125. grid.XLabelIn = false
  126. grid.YLabelIn = false
  127. grid.XLabelRotate = false
  128. grid.XDiv = 10
  129. grid.YDiv = 10
  130. grid.ClrText = RGBAType{R: 0, G: 0, B: 0, Alpha: 1}
  131. grid.ClrMain = RGBAType{R: 128, G: 160, B: 128, Alpha: 1}
  132. grid.ClrSub = RGBAType{R: 192, G: 224, B: 192, Alpha: 1}
  133. grid.WdMain = 0.1
  134. grid.WdSub = 0.1
  135. grid.YTickStr = defaultFormatter
  136. grid.XTickStr = defaultFormatter
  137. return
  138. }
  139. // WdAbs returns the absolute value of dataWd, specified in logical data units,
  140. // that has been converted to the unit of measure specified in New().
  141. func (g GridType) WdAbs(dataWd float64) float64 {
  142. return math.Abs(g.xm * dataWd)
  143. }
  144. // Wd converts dataWd, specified in logical data units, to the unit of measure
  145. // specified in New().
  146. func (g GridType) Wd(dataWd float64) float64 {
  147. return g.xm * dataWd
  148. }
  149. // XY converts dataX and dataY, specified in logical data units, to the X and Y
  150. // position on the current page.
  151. func (g GridType) XY(dataX, dataY float64) (x, y float64) {
  152. return g.xm*dataX + g.xb, g.ym*dataY + g.yb
  153. }
  154. // Pos returns the point, in page units, indicated by the relative positions
  155. // xRel and yRel. These are values between 0 and 1. xRel specifies the relative
  156. // position between the grid's left and right edges. yRel specifies the
  157. // relative position between the grid's bottom and top edges.
  158. func (g GridType) Pos(xRel, yRel float64) (x, y float64) {
  159. x = g.w*xRel + g.x
  160. y = g.h*(1-yRel) + g.y
  161. return
  162. }
  163. // X converts dataX, specified in logical data units, to the X position on the
  164. // current page.
  165. func (g GridType) X(dataX float64) float64 {
  166. return g.xm*dataX + g.xb
  167. }
  168. // HtAbs returns the absolute value of dataHt, specified in logical data units,
  169. // that has been converted to the unit of measure specified in New().
  170. func (g GridType) HtAbs(dataHt float64) float64 {
  171. return math.Abs(g.ym * dataHt)
  172. }
  173. // Ht converts dataHt, specified in logical data units, to the unit of measure
  174. // specified in New().
  175. func (g GridType) Ht(dataHt float64) float64 {
  176. return g.ym * dataHt
  177. }
  178. // Y converts dataY, specified in logical data units, to the Y position on the
  179. // current page.
  180. func (g GridType) Y(dataY float64) float64 {
  181. return g.ym*dataY + g.yb
  182. }
  183. // XRange returns the minimum and maximum values for the current tickmark
  184. // sequence. These correspond to the data values of the graph's left and right
  185. // edges.
  186. func (g GridType) XRange() (min, max float64) {
  187. min = g.xTicks[0]
  188. max = g.xTicks[len(g.xTicks)-1]
  189. return
  190. }
  191. // YRange returns the minimum and maximum values for the current tickmark
  192. // sequence. These correspond to the data values of the graph's bottom and top
  193. // edges.
  194. func (g GridType) YRange() (min, max float64) {
  195. min = g.yTicks[0]
  196. max = g.yTicks[len(g.yTicks)-1]
  197. return
  198. }
  199. // TickmarksContainX sets the tickmarks to be shown by Grid() in the horizontal
  200. // dimension. The argument min and max specify the minimum and maximum values
  201. // to be contained within the grid. The tickmark values that are generated are
  202. // suitable for general purpose graphs.
  203. //
  204. // See TickmarkExtentX() for an alternative to this method to be used when the
  205. // exact values of the tickmarks are to be set by the application.
  206. func (g *GridType) TickmarksContainX(min, max float64) {
  207. g.xTicks, g.xPrecision = Tickmarks(min, max)
  208. g.xm, g.xb = linearTickmark(g.xTicks, g.x, g.x+g.w)
  209. }
  210. // TickmarksContainY sets the tickmarks to be shown by Grid() in the vertical
  211. // dimension. The argument min and max specify the minimum and maximum values
  212. // to be contained within the grid. The tickmark values that are generated are
  213. // suitable for general purpose graphs.
  214. //
  215. // See TickmarkExtentY() for an alternative to this method to be used when the
  216. // exact values of the tickmarks are to be set by the application.
  217. func (g *GridType) TickmarksContainY(min, max float64) {
  218. g.yTicks, g.yPrecision = Tickmarks(min, max)
  219. g.ym, g.yb = linearTickmark(g.yTicks, g.y+g.h, g.y)
  220. }
  221. func extent(min, div float64, count int) (tm []float64, precision int) {
  222. tm = make([]float64, count+1)
  223. for j := 0; j <= count; j++ {
  224. tm[j] = min
  225. min += div
  226. }
  227. precision = TickmarkPrecision(div)
  228. return
  229. }
  230. // TickmarksExtentX sets the tickmarks to be shown by Grid() in the horizontal
  231. // dimension. count specifies number of major tickmark subdivisions to be
  232. // graphed. min specifies the leftmost data value. div specifies, in data
  233. // units, the extent of each major tickmark subdivision.
  234. //
  235. // See TickmarkContainX() for an alternative to this method to be used when
  236. // viewer-friendly tickmarks are to be determined automatically.
  237. func (g *GridType) TickmarksExtentX(min, div float64, count int) {
  238. g.xTicks, g.xPrecision = extent(min, div, count)
  239. g.xm, g.xb = linearTickmark(g.xTicks, g.x, g.x+g.w)
  240. }
  241. // TickmarksExtentY sets the tickmarks to be shown by Grid() in the vertical
  242. // dimension. count specifies number of major tickmark subdivisions to be
  243. // graphed. min specifies the bottommost data value. div specifies, in data
  244. // units, the extent of each major tickmark subdivision.
  245. //
  246. // See TickmarkContainY() for an alternative to this method to be used when
  247. // viewer-friendly tickmarks are to be determined automatically.
  248. func (g *GridType) TickmarksExtentY(min, div float64, count int) {
  249. g.yTicks, g.yPrecision = extent(min, div, count)
  250. g.ym, g.yb = linearTickmark(g.yTicks, g.y+g.h, g.y)
  251. }
  252. // func (g *GridType) SetXExtent(dataLf, paperLf, dataRt, paperRt float64) {
  253. // g.xm, g.xb = linear(dataLf, paperLf, dataRt, paperRt)
  254. // }
  255. // func (g *GridType) SetYExtent(dataTp, paperTp, dataBt, paperBt float64) {
  256. // g.ym, g.yb = linear(dataTp, paperTp, dataBt, paperBt)
  257. // }
  258. func lineAttr(pdf *Fpdf, clr RGBAType, lineWd float64) {
  259. pdf.SetLineWidth(lineWd)
  260. pdf.SetAlpha(clr.Alpha, "Normal")
  261. pdf.SetDrawColor(clr.R, clr.G, clr.B)
  262. }
  263. // Grid generates a graph-paperlike set of grid lines on the current page.
  264. func (g GridType) Grid(pdf *Fpdf) {
  265. var st StateType
  266. var yLen, xLen int
  267. var textSz, halfTextSz, yMin, yMax, xMin, xMax, yDiv, xDiv float64
  268. var str string
  269. var strOfs, strWd, tp, bt, lf, rt, drawX, drawY float64
  270. xLen = len(g.xTicks)
  271. yLen = len(g.yTicks)
  272. if xLen > 1 && yLen > 1 {
  273. st = StateGet(pdf)
  274. line := func(x1, y1, x2, y2 float64, heavy bool) {
  275. if heavy {
  276. lineAttr(pdf, g.ClrMain, g.WdMain)
  277. } else {
  278. lineAttr(pdf, g.ClrSub, g.WdSub)
  279. }
  280. pdf.Line(x1, y1, x2, y2)
  281. }
  282. textSz = pdf.PointToUnitConvert(g.TextSize)
  283. halfTextSz = textSz / 2
  284. pdf.SetAutoPageBreak(false, 0)
  285. pdf.SetFontUnitSize(textSz)
  286. strOfs = pdf.GetStringWidth("0")
  287. pdf.SetFillColor(255, 255, 255)
  288. pdf.SetCellMargin(0)
  289. xMin = g.xTicks[0]
  290. xMax = g.xTicks[xLen-1]
  291. yMin = g.yTicks[0]
  292. yMax = g.yTicks[yLen-1]
  293. lf = g.X(xMin)
  294. rt = g.X(xMax)
  295. bt = g.Y(yMin)
  296. tp = g.Y(yMax)
  297. // Verticals along X axis
  298. xDiv = g.xTicks[1] - g.xTicks[0]
  299. if g.XDiv > 0 {
  300. xDiv = xDiv / float64(g.XDiv)
  301. }
  302. xDiv = g.Wd(xDiv)
  303. for j, x := range g.xTicks {
  304. drawX = g.X(x)
  305. line(drawX, tp, drawX, bt, true)
  306. if j < xLen-1 {
  307. for k := 1; k < g.XDiv; k++ {
  308. drawX += xDiv
  309. line(drawX, tp, drawX, bt, false)
  310. }
  311. }
  312. }
  313. // Horizontals along Y axis
  314. yDiv = g.yTicks[1] - g.yTicks[0]
  315. if g.YDiv > 0 {
  316. yDiv = yDiv / float64(g.YDiv)
  317. }
  318. yDiv = g.Ht(yDiv)
  319. for j, y := range g.yTicks {
  320. drawY = g.Y(y)
  321. line(lf, drawY, rt, drawY, true)
  322. if j < yLen-1 {
  323. for k := 1; k < g.YDiv; k++ {
  324. drawY += yDiv
  325. line(lf, drawY, rt, drawY, false)
  326. }
  327. }
  328. }
  329. // X labels
  330. if g.XTickStr != nil {
  331. drawY = bt
  332. for _, x := range g.xTicks {
  333. str = g.XTickStr(x, g.xPrecision)
  334. strWd = pdf.GetStringWidth(str)
  335. drawX = g.X(x)
  336. if g.XLabelRotate {
  337. pdf.TransformBegin()
  338. pdf.TransformRotate(90, drawX, drawY)
  339. if g.XLabelIn {
  340. pdf.SetXY(drawX+strOfs, drawY-halfTextSz)
  341. } else {
  342. pdf.SetXY(drawX-strOfs-strWd, drawY-halfTextSz)
  343. }
  344. pdf.CellFormat(strWd, textSz, str, "", 0, "L", true, 0, "")
  345. pdf.TransformEnd()
  346. } else {
  347. drawX -= strWd / 2.0
  348. if g.XLabelIn {
  349. pdf.SetXY(drawX, drawY-textSz-strOfs)
  350. } else {
  351. pdf.SetXY(drawX, drawY+strOfs)
  352. }
  353. pdf.CellFormat(strWd, textSz, str, "", 0, "L", true, 0, "")
  354. }
  355. }
  356. }
  357. // Y labels
  358. if g.YTickStr != nil {
  359. drawX = lf
  360. for _, y := range g.yTicks {
  361. // str = strconv.FormatFloat(y, 'f', g.yPrecision, 64)
  362. str = g.YTickStr(y, g.yPrecision)
  363. strWd = pdf.GetStringWidth(str)
  364. if g.YLabelIn {
  365. pdf.SetXY(drawX+strOfs, g.Y(y)-halfTextSz)
  366. } else {
  367. pdf.SetXY(lf-strOfs-strWd, g.Y(y)-halfTextSz)
  368. }
  369. pdf.CellFormat(strWd, textSz, str, "", 0, "L", true, 0, "")
  370. }
  371. }
  372. // Restore drawing attributes
  373. st.Put(pdf)
  374. }
  375. }
  376. // Plot plots a series of count line segments from xMin to xMax. It repeatedly
  377. // calls fnc(x) to retrieve the y value associate with x. The currently
  378. // selected line drawing attributes are used.
  379. func (g GridType) Plot(pdf *Fpdf, xMin, xMax float64, count int, fnc func(x float64) (y float64)) {
  380. if count > 0 {
  381. var x, delta, drawX0, drawY0, drawX1, drawY1 float64
  382. delta = (xMax - xMin) / float64(count)
  383. x = xMin
  384. for j := 0; j <= count; j++ {
  385. if j == 0 {
  386. drawX1 = g.X(x)
  387. drawY1 = g.Y(fnc(x))
  388. } else {
  389. pdf.Line(drawX0, drawY0, drawX1, drawY1)
  390. }
  391. x += delta
  392. drawX0 = drawX1
  393. drawY0 = drawY1
  394. drawX1 = g.X(x)
  395. drawY1 = g.Y(fnc(x))
  396. }
  397. }
  398. }