iPhone button with non-rectangle shape?

Like the others say you should have a reasonable surface for registering touch events, but I’m sure you know that and have your reasons so I’ll just tell you how I did it:

I needed to do this not so long ago and what I did is what Sixten Otto just suggested. There are some hints in my original question (“UPDATE” section) for getting the alpha value for your image at a certain point:

How to create a transparent window with non-rectangular buttons?

Edit: I suggest subclassing UIControl in the example below but if you don’t need any special behavior on your button apart from the “non-rectangleness” of it then just subclassing a borderless UIButton set up with your PNG will do the job and require less work. You have more control on the control’s behavior by subclassing UIControl and doing it the “hard way” though.

I would suggest that you subclass UIControl and override the touch event methods, then check for alpha under the tapped point and not handle the event if alpha == 0. For drawing you override drawRect: and use the NSImage‘s drawInRect:fromRec:operation:fraction: method in there to draw your image in the control’s frame.

First you need to load the image and get a bitmap representation of it:

buttonImage = [NSImage imageNamed:@"myButtonImage"];
buttonImageRep = [[buttonImage representations] objectAtIndex:0];

Then you can draw it to the control’s view: (where stateImage is a pointer to the image that must be drawn depending on if the button is pressed or not)

- (void)drawRect:(NSRect)aRect {
 [stateImage drawInRect:[self bounds] fromRect:NSMakeRect(0.0,0.0,[buttonImage size].width,[buttonImage size].height)
      operation:NSCompositeSourceOver fraction:1.0];
}

At this point you have drawn your button with your png image. You can override the touch event methods and handle the event if the alpha is not 0:

NSColor *colorUnderMouse = [buttonImageRep colorAtX:mouse.x y:mouse.y];
float alpha = [colorUnderMouse alphaComponent];

That’s what I did and it works wonderfully. Hope this helps!

N.B: My example is for the Mac but it should also work on the iPhone, maybe with some slight modifications.

Leave a Comment