Reputation: 553
I'm trying to write a number inside of an image of a block. I've been looking up how to do this, and I found a couple different ways to do it. Problem is, neither of them work. I've tried this and this, but they both cause an error in the contact log that says invalid context 0x0
. Anyone know what can cause that?
EDIT:
I should probably mention where I'm trying to implement this. I have a class called Blok
that extends NSObject and holds a UIImage. That UIImage is used in another class's drawRect
method, and is also what I want to have text on.
Here's where I initialize the image:
-(id)initWithType:(NSString*)theType andSymbol:(NSString*)theSymbol {
self = [super init];
if (self) {
image = [[UIImage alloc] init];
type = theType;
symbol = theSymbol;
}
return self;
}
And here is where it gets set later on:
-(void)setImage:(UIImage*)theImage {
image = theImage;
image = [self addText:symbol atPoint:CGPointMake(0, 0) withFont:[UIFont fontWithName:@"Helvetica" size:12] ofColor:[UIColor blackColor]];
}
The method call is to the method shown below, given by H2CO3:
- (UIImage *) addText: (NSString *) str atPoint: (CGPoint) point withFont: (UIFont *) font ofColor: (UIColor *) color {
int w = image.size.width;
int h = image.size.height;
// create empty bitmap context
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB ();
CGContextRef ctx = CGBitmapContextCreate (NULL, w, h, 8, w * 4, colorSpace, kCGImageAlphaPremultipliedFirst);
CGContextSetInterpolationQuality (ctx, kCGInterpolationHigh);
// draw the image and the text on the bitmap context
CGContextDrawImage (ctx, CGRectMake (0, 0, h, w), image.CGImage);
char *text = (char *)[str cStringUsingEncoding: NSASCIIStringEncoding];
CGContextSetTextDrawingMode (ctx, kCGTextFill);
CGFloat *comp = CGColorGetComponents ([color CGColor]);
CGContextSetRGBFillColor (ctx, comp[0], comp[1], comp[2], comp[3]);
CGContextSelectFont (ctx, [[font fontName] UTF8String], [font pointSize], kCGEncodingMacRoman);
CGContextShowTextAtPoint (ctx, point.x, h - point.y, text, strlen (text));
// get the image as a UIImage and clean up
CGImageRef imageMasked = CGBitmapContextCreateImage (ctx);
UIImage *img = [UIImage imageWithCGImage: imageMasked];
CGContextRelease (ctx);
CGImageRelease (imageMasked);
CGColorSpaceRelease (colorSpace);
return img;
}
I tweaked it a bit to suit the program. Unfortunately, this seems to be causing a bad access error...
Upvotes: 1
Views: 2163
Reputation: 553
After dealing with this a little longer than I would like, I'm just going to use a UILabel in the drawRect
method.
EDIT: Using drawAtPoint
in the drawRect
method, working just fine now.
Upvotes: 0
Reputation:
See how I implemented this here: https://github.com/H2CO3/UIImage-Editor/blob/master/UIImage%2BEditor.m
Especially, take a look at the
- (UIImage *) addText: (NSString *) str atPoint: (CGPoint) point withFont: (UIFont *) font ofColor: (UIColor *) color
method.
Upvotes: 2