Module: AspectRatio

Defined in:
lib/aspect_ratio.rb

Class Method Summary collapse

Class Method Details

.crop(x, y, r) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/aspect_ratio.rb', line 24

def self.crop(x, y, r)
  orient = r.split('!')[1]
  ratio  = r.split('!')[0].split(':').sort.map { |r| BigDecimal(r) }

  vertical = y > x
  rotate = y > x && orient == 'h' || x > y && orient == 'v'

  if (vertical || rotate) && !(vertical && rotate)
    x = x + y
    y = x - y
    x = x - y
  end

   = x
   = x * (ratio[1] / ratio[0])

  if ( > y) || rotate && ( > x)
     = y
     = y * (ratio[1] / ratio[0])

    if  > x
       = x
       = x * (ratio[0] / ratio[1])
    end
  end

  Δx = ((x - ) / 2).to_f.floor
  Δy = ((y - ) / 2).to_f.floor

  if (vertical || rotate) && !(vertical && rotate)
    [
      Δy,         # crop top left x
      Δx,         # crop top left y
      y - Δy * 2, # crop width
      x - Δx * 2  # crop height
    ]
  else
    [
      Δx.to_f,    # crop top left x
      Δy,         # crop top left y
      x - Δx * 2, # crop width
      y - Δy * 2  # crop height
    ]
  end
end

.resize(x, y, x_max = nil, y_max = nil) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/aspect_ratio.rb', line 4

def self.resize(x, y, x_max = nil, y_max = nil)
  x = BigDecimal(x)
  y = BigDecimal(y)

  if x_max && y_max
    # Maximum values of height and width given, aspect ratio preserved.
    if y > x
      return [(y_max * x / y).round, y_max]
    else
      return [x_max, (x_max * y / x).round]
    end
  elsif x_max
    # Width given, height automagically selected to preserve aspect ratio.
    return [x_max, (x_max * y / x).round]
  else
    # Height given, width automagically selected to preserve aspect ratio.
    return [(y_max * x / y).round, y_max]
  end
end