This commit is contained in:
Will Charczuk 2016-07-11 18:48:51 -07:00
parent 01983f4e86
commit 9a5138b21d
17 changed files with 477 additions and 308 deletions

View file

@ -3,8 +3,6 @@ package chart
import (
"math"
"sort"
"github.com/wcharczuk/go-chart/drawing"
)
// XAxis represents the horizontal axis.
@ -57,13 +55,46 @@ func (xa XAxis) getTickCount(r Renderer, ra Range, vf ValueFormatter) int {
if len(ln) > len(l0) {
ll = ln
}
llw, _ := r.MeasureText(ll)
textWidth := drawing.PointsToPixels(r.GetDPI(), float64(llw))
llb := r.MeasureText(ll)
textWidth := llb.Width
width := textWidth + DefaultMinimumTickHorizontalSpacing
count := int(math.Ceil(float64(ra.Domain) / float64(width)))
return count
}
// Measure returns the bounds of the axis.
func (xa XAxis) Measure(r Renderer, canvasBox Box, ra Range, ticks []Tick) Box {
defaultFont, _ := GetDefaultFont()
r.SetFont(xa.Style.GetFont(defaultFont))
r.SetFontSize(xa.Style.GetFontSize(DefaultFontSize))
sort.Sort(Ticks(ticks))
var left, right, top, bottom = math.MaxInt32, 0, math.MaxInt32, 0
for _, t := range ticks {
v := t.Value
lx := ra.Translate(v)
tb := r.MeasureText(t.Label)
tx := canvasBox.Left + lx
ty := canvasBox.Bottom + DefaultXAxisMargin + tb.Height
top = MinInt(top, canvasBox.Bottom)
left = MinInt(left, tx-(tb.Width>>1))
right = MaxInt(right, tx+(tb.Width>>1))
bottom = MaxInt(bottom, ty)
}
return Box{
Top: top,
Left: left,
Right: right,
Bottom: bottom,
Width: right - left,
Height: bottom - top,
}
}
// Render renders the axis
func (xa XAxis) Render(r Renderer, canvasBox Box, ra Range, ticks []Tick) {
tickFontSize := xa.Style.GetFontSize(DefaultFontSize)
@ -80,18 +111,16 @@ func (xa XAxis) Render(r Renderer, canvasBox Box, ra Range, ticks []Tick) {
sort.Sort(Ticks(ticks))
var textHeight int
for _, t := range ticks {
_, th := r.MeasureText(t.Label)
if th > textHeight {
textHeight = th
}
}
ty := canvasBox.Bottom + DefaultXAxisMargin + int(textHeight)
for _, t := range ticks {
v := t.Value
x := ra.Translate(v)
tx := canvasBox.Right - x
r.Text(t.Label, tx, ty)
lx := ra.Translate(v)
tb := r.MeasureText(t.Label)
tx := canvasBox.Left + lx
ty := canvasBox.Bottom + DefaultXAxisMargin + tb.Height
r.Text(t.Label, tx-tb.Width>>1, ty)
r.MoveTo(tx, canvasBox.Bottom)
r.LineTo(tx, canvasBox.Bottom+DefaultVerticalTickHeight)
r.Stroke()
}
}