I am trying to use CoreText on iOS to render OpenGL textures. CoreText renders in a CoreGraphics Bitmap context, which is then loaded in OpenGL using glTexImage2D
.
When I create a bitmap context using an RGB color space evertyhing works fine
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
uint8_t *data = (uint8_t *)calloc(height, 4 * width);
CGContextRef context = CGBitmapContextCreate(data, width, height, 8, 4 * width, colorSpace, kCGImageAlphaNoneSkipLast);
CGColorSpaceRelease(colorSpace);
However, I would like to use a grayscale only color space. When I do the text does not appear.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
uint8_t *data = (uint8_t *)calloc(height, width);
CGContextRef context = CGBitmapContextCreate(data, width, height, 8, width, colorSpace, kCGImageAlphaNone);
CGColorSpaceRelease(colorSpace);
The text I am rendering is black. In both cases I can draw in the context using CoreGraphics methods.
I draw the text using the fllowing code:
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)text);
CGSize dimensions = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, [text length]), NULL, CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX), NULL);
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, dimensions.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGRect box = CGRectMake(0, 0, dimensions.width, dimensions.height);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, box );
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, [text length]), path, NULL);
CTFrameDraw(frame, context);
CFRelease(frame);
CFRelease(path);
CFRelease(framesetter);
Is there a special setting in CoreText to make this work ?
Thanks
OK, i managed to reproduce the problem. In your NSAttributeString property dictionary, you shouldn't use a UIColor (NSColor?), but a CGColorRef. This way the CGContext
APIs will know how to treat your color depending on the colorspace. If you just do the following, you should be ok to go.
CGColorRef col = [UIColor blackColor].CGColor;
NSDictionary *attributesDict = [NSDictionary dictionaryWithObjectsAndKeys:
//whatever attributes you need
col, kCTForegroundColorAttributeName,
nil];
NSAttributedString *stringToDraw = [[NSAttributedString alloc] initWithString:yourText
attributes:attributesDict];
I hope this helps, let me know if it works!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.