Last Updated: February 25, 2016
·
918
· lucabernardi

Prevent CGRect fractional value to cause blurry rendering

It always surprise me how things that appear simple are in fact more complex, and it’s very easy to forget about it.

CGRect is one of this kind of things. There are two facts about CGRect that I’m prone to forget:

  1. Width and Height don’t have to be positive, they can be negative and all Apple’s functions that deal with CGRect handle correctly both case. (I have to publicly admin: mine not always behave properly)

  2. All the CGRect’s field are CGFloat, this means that if you do some math on this field you can end up with a fractional values.

Speaking about the second case if you try to render a view that have a fractional value in its frame property you will probably end up with a blur rendering or pixelation. This happens because CocoaTouch layout typically happens on whole point boundaries, and if it encounter fractional value need to start the antialiasing.

“There’s a function for that” and this function is called CGRectIntegral, as you can see in Apple’ Doc this function round the origin’s value to the nearest integer value. So if you to some math on CGRect you should consider to “clean up” the value with CGRectIntegral.