Last active
November 21, 2015 11:12
-
-
Save bdewater/e3d735edd2533d4e7cea to your computer and use it in GitHub Desktop.
Calculate screen pixel density
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'bigdecimal' | |
# https://en.wikipedia.org/wiki/Pixel_density#Calculation_of_monitor_PPI | |
def calculate_ppi(height_pixels, width_pixels, diagonal_inches) | |
diagonal_pixels = Math.sqrt((height_pixels**2) + (width_pixels**2)) | |
ppi = diagonal_pixels / diagonal_inches | |
end | |
def calculate_ppi_rounded(height_pixels, width_pixels, diagonal_inches) | |
ppi = calculate_ppi(height_pixels, width_pixels, diagonal_inches) | |
arg_digits = [height_pixels, width_pixels, diagonal_inches].collect(&:to_s).collect { |x| x.gsub(/\D/, '' )}.collect(&:length) | |
significant_digits = arg_digits.min | |
BigDecimal.new(ppi, significant_digits).to_i | |
end | |
# A Dell P2715Q monitor | |
puts calculate_ppi(3840, 2160, 27.0) # 163.17830889498507 | |
puts calculate_ppi_rounded(3840, 2160, 27.0) # 163 | |
# A MacBook Pro 13.3 with Retina display | |
puts calculate_ppi(2560, 1600, 13.3) # 226.98300468106115 | |
puts calculate_ppi_rounded(2560, 1600, 13.3) # 227 | |
# An iPhone 5 with Retina display | |
puts calculate_ppi(1136, 640, 4.0) # 325.9693237100694 | |
puts calculate_ppi_rounded(1136, 640, 4.0) # 330 - only two significant digits |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment