Skip to content

Instantly share code, notes, and snippets.

@Tricertops
Created April 29, 2013 17:49
Show Gist options
  • Save Tricertops/5483361 to your computer and use it in GitHub Desktop.
Save Tricertops/5483361 to your computer and use it in GitHub Desktop.
Helper functions to round screen coordinates and dimensions to screen scale.
CGFloat CGFloatAdjustToScreenScale(CGFloat value, NSRoundingMode mode) {
CGFloat (*roundingFunction)(CGFloat);
switch (mode) {
case NSRoundPlain: roundingFunction = &roundf; break;
case NSRoundUp: roundingFunction = &ceilf; break;
case NSRoundDown: roundingFunction = &floorf; break;
case NSRoundBankers:roundingFunction = &roundf; break;
}
CGFloat scale = [[UIScreen mainScreen] scale];
CGFloat result = roundingFunction(value * scale) / scale;
return result;
}
CGPoint CGPointAdjustToScreenScale(CGPoint point, NSRoundingMode mode) {
return CGPointMake(CGFloatAdjustToScreenScale(point.x, mode),
CGFloatAdjustToScreenScale(point.y, mode));
}
CGSize CGSizeAdjustToScreenScale(CGSize size, NSRoundingMode mode) {
return CGSizeMake(CGFloatAdjustToScreenScale(size.width, mode),
CGFloatAdjustToScreenScale(size.height, mode));
}
CGRect CGRectAdjustToScreenScale(CGRect rect, NSRoundingMode mode) {
return CGRectMake(CGFloatAdjustToScreenScale(rect.origin.x, mode),
CGFloatAdjustToScreenScale(rect.origin.y, mode),
CGFloatAdjustToScreenScale(rect.size.width, mode),
CGFloatAdjustToScreenScale(rect.size.height, mode));
}
// Example
CGFloat value = 3.61;
// On non-Retina screens with scale 1:
CGFloat nonRetina = CGFloatAdjustToScreenScale( value, NSRoundPlain );
// nonRetina is equal to 4
// On Retina screens with scale 2:
CGFloat retina = CGFloatAdjustToScreenScale( value, NSRoundPlain );
// retina is equal to 3.5
// Use different values for rounding mode, based on what you want to achieve.
// NSRoundUp is good for fitting sizes, because it will never return smaller values.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment