Pregunta

Is there a way to draw text in an NSBitMapImageRep with sub-pixel anti-aliasing? The text is drawn on an opaque white background and I've tried using the CGContextSetShouldSmoothFonts function, but that doesn't seem to help.

NSBitmapImageRep *bm = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL pixelsWide:300 pixelsHigh:300 bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSCalibratedRGBColorSpace bytesPerRow:0 bitsPerPixel:0];
[NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithBitmapImageRep:bm]];
[[NSColor whiteColor] set];
NSRectFill(NSMakeRect(0, 0, 300, 300));
CGContextRef ctx = NSGraphicsContext.currentContext.graphicsPort;
CGContextSetShouldSmoothFonts(ctx, true);
[@"Example" drawAtPoint:NSZeroPoint withAttributes:nil];
[[bm TIFFRepresentation] writeToFile:[@"~/Desktop/bitmap.tiff" stringByExpandingTildeInPath] atomically:NO];

I can get text smoothing to work when I draw in an NSImage using -[NSImage lockFocus], but that isn't reliable when running it on a Retina display.

¿Fue útil?

Solución

I ended up using this alternative code to get text smoothing:

CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
CGContextRef c = CGBitmapContextCreate(NULL, 300, 300, 8, 300 * 4, cs, kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);
[NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:c flipped:NO]];
[[NSColor whiteColor] set];
NSRectFill(NSMakeRect(0, 0, 300, 300));
[@"Example" drawAtPoint:NSZeroPoint withAttributes:nil];
CGImageRef cgImage = CGBitmapContextCreateImage(c);
NSImage *im = [[NSImage alloc] initWithCGImage:cgImage size:NSZeroSize];
[[im TIFFRepresentation] writeToFile:[@"~/Desktop/cgImage.tiff" stringByExpandingTildeInPath] atomically:NO];
CGImageRelease(cgImage);
CGColorSpaceRelease(cs);
CGContextRelease(c);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top