You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.6KB

  1. require_relative '../control'
  2. module DHE
  3. class Label < Control
  4. BASELINES = {above: 'alphabetic', below: 'hanging', right_of: 'middle'}
  5. ANCHORS = {above: 'middle', below: 'middle', right_of: 'start'}
  6. ASCENT_RATIO = 2.0 / 3.0 # Approximately correct for Proxima Nova font
  7. SIZES = {title: 12.0 / PX_PER_MM, large: 9.0 / PX_PER_MM, small: 7.0 / PX_PER_MM}
  8. def initialize(faceplate:, text:, size:, x:, y:, style: :normal, alignment: :above, transform: :upper)
  9. @x = x
  10. @y = y
  11. @text = text
  12. @size = SIZES[size.to_sym]
  13. @color = style == :normal ? faceplate.foreground : faceplate.background
  14. @alignment = alignment
  15. @baseline = BASELINES[@alignment]
  16. @anchor = ANCHORS[@alignment]
  17. height = @size * ASCENT_RATIO
  18. width = @text.length * @size * 0.6 # Approximate
  19. left = case alignment
  20. when :right_of
  21. x
  22. else # above or below
  23. x - width / 2
  24. end
  25. top = case alignment
  26. when :above
  27. y - height
  28. when :right_of
  29. y - height / 2
  30. else # below
  31. y
  32. end
  33. bottom = top + height
  34. right = left + width
  35. super(faceplate: faceplate, x: x, y: y, top: top, right: right, bottom: bottom, left: left)
  36. end
  37. def draw(svg:, x:, y:)
  38. svg.text(x: x, y: y, 'dominant-baseline' => @baseline, 'text-anchor' => @anchor, fill: @color, style: "font-family:Proxima Nova;font-weight:bold;font-size:#{@size}px") do |text|
  39. text << @text
  40. end
  41. end
  42. end
  43. end