0

I have this code, to draw some text inside a (so far) simple button:

UIImage *buttonImage(CGRect bounds, UIColor *fillColor, NSString *title) {

    UIGraphicsBeginImageContextWithOptions(bounds.size, NO, 0);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, fillColor.CGColor);
    CGContextFillRect(context, bounds);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);

    [title drawInRect:bounds withFont:PanelButtonFont];

    UIGraphicsEndImageContext();

    return image;
}

The problematic part is the drawInRect. It's simply not drawing my text. The font is correct, and I've tested this with normal font code there, so it's not that. I think perhaps it doesn't realise that I want it to draw it onto the image that it's producing?

Andrew
  • 15,935
  • 28
  • 121
  • 203

1 Answers1

2

Just change the order and get the image after you draw the text:

UIImage *buttonImage(CGRect bounds, UIColor *fillColor, NSString *title) {

UIGraphicsBeginImageContextWithOptions(bounds.size, NO, 0);

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSetFillColorWithColor(context, fillColor.CGColor);
CGContextFillRect(context, bounds);

CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);

[title drawInRect:bounds withFont:PanelButtonFont];

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return image;

}

Antonio MG
  • 20,382
  • 3
  • 43
  • 62