Class: DynamicImage::ImageSizing
- Inherits:
-
Object
- Object
- DynamicImage::ImageSizing
- Defined in:
- lib/dynamic_image/image_sizing.rb
Overview
DynamicImage Image Sizing
Calculates cropping and fitting for image sizes. The helpers use it to work out the dimensions of a rendered image, and it can be used on its own when you need the size without rendering anything: reserving space in a layout, filling in og:image:width, or laying out a PDF.
Instance Method Summary collapse
-
#available_width(ratio = nil) ⇒ Integer
Returns the widest the image can be rendered at, in pixels.
-
#crop_geometry(ratio_vector) ⇒ Array(Vector2d, Vector2d)
Calculates crop geometry.
-
#fit(fit_size, options = {}) ⇒ Vector2d
Adjusts
fit_sizeto fit the image dimensions. -
#initialize(record, options = {}) ⇒ ImageSizing
constructor
A new instance of ImageSizing.
Constructor Details
#initialize(record, options = {}) ⇒ ImageSizing
Returns a new instance of ImageSizing.
17 18 19 20 |
# File 'lib/dynamic_image/image_sizing.rb', line 17 def initialize(record, = {}) @record = record @uncropped = [:uncropped] ? true : false end |
Instance Method Details
#available_width(ratio = nil) ⇒ Integer
Returns the widest the image can be rendered at, in pixels.
Without a ratio this is the image's own width. With one it is the width of the largest crop matching that ratio.
65 66 67 68 69 70 |
# File 'lib/dynamic_image/image_sizing.rb', line 65 def available_width(ratio = nil) ratio = DynamicImage::Ratio.parse(ratio) return size.x.floor unless ratio crop_geometry(vector(ratio, 1)).first.x.floor end |
#crop_geometry(ratio_vector) ⇒ Array(Vector2d, Vector2d)
Calculates crop geometry. The given vector is scaled to match the image size, since cropping happens before resizing.
The crop is positioned to keep the record's crop gravity as close to the center as possible, clamped to the bounds of the image.
37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/dynamic_image/image_sizing.rb', line 37 def crop_geometry(ratio_vector) # Maximize the crop area to fit the image size crop_size = ratio_vector.fit(size).round # Ignore pixels outside the pre-cropped area for now center = crop_gravity - crop_start start = center - (crop_size / 2).floor start = clamp(start, crop_size, size) [crop_size, (start + crop_start)] end |
#fit(fit_size, options = {}) ⇒ Vector2d
Adjusts fit_size to fit the image dimensions. Any dimension set to zero will be ignored.
99 100 101 102 103 104 105 |
# File 'lib/dynamic_image/image_sizing.rb', line 99 def fit(fit_size, = {}) fit_size = parse_vector(fit_size) require_dimensions!(fit_size) if [:crop] fit_size = size.fit(fit_size) unless [:crop] fit_size = size.contain(fit_size) unless [:upscale] fit_size end |