Using fractional pixels to position UIImageViews
When centering content vertically and/or horizontally in a view, I often use a simple formula to calculate the x/y values for the content’s frame:
(container.frame.size.height - image.frame.size.height)/2
The problem with using this formula for UIImageViews is that, if one or more of the dimensions is an odd value, the result will be a fractional value. When a UIImageView has a fractional value in the frame’s origin, iOS will attempt to anti-alias the image to make it appear at that fractional position. Unfortunately, this usually isn’t what you want.
In the screenshots at right, on the left the three top icons have fractional x and y values, and the bottom icon has a fractional y value. As you can see, those icons appear blurry.
On the right, I’ve rounded the values down using floor(). They still appear to be centered, but the icons are crisp, and the
overall effect is much better.
Here’s the updated code:
You can find macros for centering a view in its parent, among other goodies, in the macros header I include in all of my iOS projects.