Wednesday, 4 August 2010

UIGlassButton Generator in MonoTouch

Sometimes the default look of iOS controls (such as UIButton) is a little 'flat'. Apple themselves sometimes use a very pretty 'glass button' effect, which could be achieved (apparently, I'm paraphrasing here) using an undocumented UIGlassButton class. You can read more about this in the source links for this sample:
Anyway... Martin did a great job porting this approach to MonoTouch, creating a GlassButton.dll wrapper as part of a sample project that allows you to create great-looking PNG-image-glass-buttons to incorporate into your iOS projects. The only thing missing was a double-resolution version for my new iPhone4's Retina Display, so that's what I've added to this github project: GlassButtonGenerator.

How it works:
  1. Edit the string constants for button text and filename
  2. Edit the filename which is used in the path to save the output
  3. Run the app in the Simulator and press the [Generate Glass Button] button
  4. Grab the images that are saved to your Desktop
  5. Use the images in your iOS app in UIButton controls
Here is the 'output' when you are running it in the simulator (the button images should be saved to your Desktop):

If you are then wondering what to do with the two images, check out Miguel's post on Building apps for the Retina Display. Basically you should use UIImage.FromBundle to load the image and ensure that the 'regular' and 'retina' versions have the same filename (with the 'retina' version having a suffix @2x).

For the code below, the /Images/ folder has four images: BuyGlass.png, BuyGlass@2x.png, CancelGlass.png, CancelGlass@2x.png (where the @2x images have double the height & width dimensions of the base image)...
   , UIControlState.Normal);
   , UIControlState.Normal);

Don't forget to make the Build Action: Content for your image files! And remember, DON'T use UIGlassButton in your apps directly - generate the images and include them.

UPDATE (May 2011): Miguel has posted a code-based glass button implementation which you might prefer to this pre-generated image one. See Glass button for iPhone and the code on github.