iOS: irregular shaped buttons (shaped button fix)
I’m creating an app where I really wanted to have buttons that were not a standard rectangle shape. Even if you create these non standard shape buttons, (although Xcode preserves the transparency), it still thinks there is a rectangle area to click, so you get a bad overlap making your buttons not behave in the expected or desired manor.

The red box shows the border Xcode has set, believing that to be my rectangle shape – when I only want the surface area shown by the diagonal lines.
This can be fixed with writing code to define the exact areas to click, and there are tutorials online to help with that. I found a fantastic Class already written though and that is what I will be implementing in my project.
You create the button in the shape that you want, so mine is this irregular rectangle.
Save it as a single image, and be sure to have transparency, and then save as a .png file.
Put the image into your project as you normally would. Then after searching and getting a bit of headache looking at all the “math” and calculations to enable this, I came across a brilliant post via Jeff LaMarche site through the comments on this post was one detailing how he was going to link to oleb.net (Ole Begemann) which is ultimately the code I used came from.
Defining the image on the app, you can still see the defined custom button rectangle shape.

The Class he wrote, called OBShapedButton will do all the hard work for you, have a read through to get a look at how it works then add the 4 files to your project (OBShapedButton.h, OBShapedButton.m, UIImage+ColorAtPixel.h and UIImage+ColorAtPixel.m). The image to the right is the Class setting in Xcode 4.
Then set the Class of your buttons to this new Class OBShapedButton. I tried it for this new project I am working on and it works a treat.
The code was updated in April.
Resources: http://oleb.net/blog/2009/10/obshapedbutton-non-rectangular-buttons-on-the-iphone/ for the code explanation.
https://github.com/ole/OBShapedButton The class on GitHub.
No related posts.


0 Comments