我正在尝试在块的图像内写入一个数字。我一直在寻找如何做到这一点,我发现有几种不同的方式来做到这一点。问题是,他们都没有工作。我试过this和this,但它们都在导致invalid context 0x0
的联系日志中导致错误。任何人都知道可能会导致什么?编辑:将文本写入UIImage
我应该提到我试图实现这一点。我有一个名为Blok
的类,它扩展NSObject并保存UIImage。该UIImage在另一个课程的drawRect
方法中使用,也是我想要的文本。
这里就是我初始化图像:
-(id)initWithType:(NSString*)theType andSymbol:(NSString*)theSymbol {
self = [super init];
if (self) {
image = [[UIImage alloc] init];
type = theType;
symbol = theSymbol;
}
return self;
}
这里是它获取设置以后:
-(void)setImage:(UIImage*)theImage {
image = theImage;
image = [self addText:symbol atPoint:CGPointMake(0, 0) withFont:[UIFont fontWithName:@"Helvetica" size:12] ofColor:[UIColor blackColor]];
}
方法调用是由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;
}
我调整了一下,以适应程序。不幸的是,这似乎造成了恶劣访问错误......
好的,这似乎工作。它不喜欢'CGAffineTransform transform = [self transformForOrientation:self.size];',所以我将它与引用它的行一起取出。尽管保留drawImage行。它通过了没有任何实际问题,但现在我得到了可怕的'EXC_BAD_ACCESS'错误> _ <我会接受你的答案,当我可以解决这个错误... – RaysonK
何时何地发生错误?该错误肯定不在我的代码中,因为它经过多次测试和使用。我帮你解决这个问题,但你必须提供更多信息。 – 2012-06-01 18:11:45
这就是问题所在,是我无法确定导致错误的部分。我经过调试器,它看起来像程序工作正常,但它在后台代码(而不是我正在编写的代码,但'引擎盖下'的东西),导致错误的命中行。 – RaysonK