Boon
Boon

Reputation: 41490

How to create custom image for UIButton using code?

I want to use custom code to draw the image for UIButton. How do I go about doing that? I have the code that can go into drawRect, but that's for UIView, not UIButton.

In the Custom view's drawRect:

@implement MyCustomView

- (void)drawRect:(CGRect)rect {
    UIColor *color = [UIColor blueColor];

   // Vertical stroke
   {
        UIBezierPath *bezierPath = [UIBezierPath bezierPath];
        [bezierPath moveToPoint: CGPointMake(20, 0)];
        [bezierPath addLineToPoint: CGPointMake(20, 40)];
        [color setStroke];
        bezierPath.lineWidth = 1;
        [bezierPath stroke];
    }
}

- (UIImage *)imageFromView {
        [self drawRect:CGRectMake(0, 0, 40, 40)];

        UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0.0);
        [self.layer renderInContext:UIGraphicsGetCurrentContext()];

        UIImage *img = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();

        return img;
    }

In the button code:

UIButton *button = [[UIButton alloc] init];
MyCustomView *view = [[MyCustomView alloc] init];
[button setImage:view.imageFromView forState:UIControlStateNormal];

Upvotes: 0

Views: 552

Answers (1)

matt
matt

Reputation: 535274

  1. Use your drawing code to draw into an image graphics context opened with UIGraphicsBeginImageContextWithOptions.

  2. Pull out the image using UIGraphicsGetImageFromCurrentImageContext.

  3. Close the image graphics context with UIGraphicsEndImageContext.

  4. Use the image in the button.

Simple example:

UIGraphicsBeginImageContextWithOptions(CGSizeMake(100,100), NO, 0);
UIBezierPath* p =
    [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0,0,100,100)];
[[UIColor blueColor] setFill];
[p fill];
UIImage* im = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// im is the blue circle image, do something with it here ...

Upvotes: 3

Related Questions