Anti-aliasing rotated UIViews
10/01/2011 § 4 Comments
It is being a lot of time I don’t add a new post here, so here I am with a pretty quick post.
This history begins half year ago, when I worked on the Chatter app for iPad with my dear friend Didier Prophete. I worked on an anti-aliasing solution for a rotated image that I was pretty eager to publish but I couldn’t do it at the time.
Yesterday I was working on a Pinch Spread component (yes, just like Chatter does but without the pan part and for a different reason) at nKey for using on some of our apps, and I needed to use that old solution but I couldn’t remember it, so I had to come up with a simpler one since I was on a run due to other matters.
Going (finally) straight to the point, when you rotate an UIView it’s borders become serrated so that you need to anti-alias them in order to look good.
So my solution was to use a container view 5 pixels wider in order to reduce the serrated effect on the view I wanted to rotate – of course, you have to center the view on the container and then rotate the container view instead.
The next step is to add a 3 pixel transparent border to the inner view and rasterize it so that the pixels interpolate smoothing the border.
view.layer.borderWidth = 3;
view.layer.borderColor =[UIColor clearColor].CGColor;
view.layer.shouldRasterize = YES;
Now the final trick is to add some shadow. This will make the border look somehow more solid. In my case I added a lot of shadow because I wanted the shadow to be very visible (the view stack for the Pinch Spread looks sharper and prettier due to the shadow effect).
view.layer.shadowOffset = CGSizeMake(0, -1);
view.layer.shadowOpacity = 1;
view.layer.shadowColor = [UIColor blackColor].CGColor;
So, by using the solution above this is what you will get:
Although it is a pretty obvious and simple solution, I hope it helps you out (and now I have a reminder for the next time!).