Creating UIButton in Image Form

how can I create a UIButton in the form of a given image.

I can create something close to it, but the image does not seem appropriate in the button. my requirement is the image below .ie; semicircle

The code I used to create the button is below.

what changes should i make in the following image to get this button. ps-add subview executed in another class.

btnStartGame =[UIButton buttonWithType:UIButtonTypeCustom]; [btnStartGame setFrame:CGRectMake(60, 200, 200, 200)]; btnStartGame.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:30]; [btnStartGame setImage: [UIImage imageNamed:@"Draw button.png"] forState:UIControlStateNormal]; btnStartGame.titleLabel.textColor=[UIColor redColor]; btnStartGame.clipsToBounds = YES; btnStartGame.layer.cornerRadius = 50;//half of the width btnStartGame.layer.borderColor=[UIColor redColor].CGColor; btnStartGame.layer.borderWidth=2.0f; btnStartGame.tag=20; btnStartGame.highlighted=NO; 
+4
source share
2 answers

Here's a great tutorial with downloadable source code:

http://iphonedevelopment.blogspot.co.uk/2010/03/irregularly-shaped-uibuttons.html

In essence, you need to create a category in UIImage that checks if the point you touched is a transparent image or not. This means that you can use it to test hit tests for irregular shapes.

Then you subclass UIButton and drag hitTest: withEvent:

Hope this helps

+2
source

Although Jeff Lamarche's solution related to another answer works fine, it uses a lot of memory and / or does a lot of work:

  • If you create NSData once in the initializer, you end up holding a relatively large block of memory for the life of each button
  • If you do this transiently, as is done in the answer, then you end up converting the entire image every time you click the test on your button - process thousands of pixels and discard the result after receiving one byte!

It turns out you can do it much more efficiently, both in terms of memory usage and in terms of CPU consumption, following the approach described in this answer .

Subclass UIButton and override its pointInside:withEvent: method as follows:

 -(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event { if (![super pointInside:point withEvent:event]) { return NO; } unsigned char pixel[1] = { 0 }; CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 1, NULL, (CGBitmapInfo)kCGImageAlphaOnly); UIGraphicsPushContext(context); UIImage *image = [self backgroundImageForState:UIControlStateNormal] ; [image drawAtPoint:CGPointMake(-point.x, -point.y)]; UIGraphicsPopContext(); CGContextRelease(context); return pixel[0] != 0; } 

The above code accepts alpha from the button background image. If your button uses a different image, change the line that initializes the image variable above.

+1
source

All Articles