Class: UnicodePlot::DensityCanvas

Inherits:
Canvas
  • Object
show all
Defined in:
src/lib/unicode_plot/canvas/density_canvas.rb

Constant Summary collapse

DENSITY_SIGNS =
[" ", "", "", "", ""].freeze
MIN_WIDTH =
5
MIN_HEIGHT =
5
X_PIXEL_PER_CHAR =
1
Y_PIXEL_PER_CHAR =
2

Constants inherited from Canvas

Canvas::CANVAS_CLASS_MAP

Constants included from StyledPrinter

StyledPrinter::COLOR_DECODE, StyledPrinter::COLOR_ENCODE, StyledPrinter::DISABLE_TEXT_STYLE, StyledPrinter::TEXT_COLORS

Instance Attribute Summary

Attributes inherited from Canvas

#height, #origin_x, #origin_y, #pixel_height, #pixel_width, #plot_height, #plot_width, #width, #x_pixel_per_char, #y_pixel_per_char

Instance Method Summary collapse

Methods inherited from Canvas

#char_at, #color_at, create, #index_at, #line!, #lines!, #point!, #points!, #print, #show

Methods included from BorderPrinter

#print_border_bottom, #print_border_top

Methods included from StyledPrinter

#print_color, #print_styled

Constructor Details

#initialize(width, height, **kw) ⇒ DensityCanvas

Returns a new instance of DensityCanvas.



13
14
15
16
17
18
19
20
21
22
23
24
# File 'src/lib/unicode_plot/canvas/density_canvas.rb', line 13

def initialize(width, height, **kw)
  width = [width, MIN_WIDTH].max
  height = [height, MIN_HEIGHT].max
  @max_density = 1
  super(width, height,
        width * X_PIXEL_PER_CHAR,
        height * Y_PIXEL_PER_CHAR,
        0,
        x_pixel_per_char: X_PIXEL_PER_CHAR,
        y_pixel_per_char: Y_PIXEL_PER_CHAR,
        **kw)
end

Instance Method Details

#pixel!(pixel_x, pixel_y, color) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'src/lib/unicode_plot/canvas/density_canvas.rb', line 26

def pixel!(pixel_x, pixel_y, color)
  unless 0 <= pixel_x && pixel_x <= pixel_width &&
         0 <= pixel_y && pixel_y <= pixel_height
    return color
  end

  pixel_x -= 1 unless pixel_x < pixel_width
  pixel_y -= 1 unless pixel_y < pixel_height

  char_x = (pixel_x.fdiv(pixel_width) * width).floor
  char_y = (pixel_y.fdiv(pixel_height) * height).floor

  index = index_at(char_x, char_y)
  @grid[index] += 1
  @max_density = [@max_density, @grid[index]].max
  @colors[index] |= COLOR_ENCODE[color]
  color
end


45
46
47
48
49
50
51
52
53
54
55
56
# File 'src/lib/unicode_plot/canvas/density_canvas.rb', line 45

def print_row(out, row_index)
  unless 0 <= row_index && row_index < height
    raise ArgumentError, "row_index out of bounds"
  end
  y = row_index
  den_sign_count = DENSITY_SIGNS.length
  val_scale = (den_sign_count - 1).fdiv(@max_density)
  (0 ... width).each do |x|
    den_index = (char_at(x, y) * val_scale).round
    print_color(out, color_at(x, y), DENSITY_SIGNS[den_index])
  end
end