NSBitmapImageRep中的子像素抗锯齿

时间:2012-06-29 12:08:47

标签: cocoa quartz-graphics nsbitmapimagerep

有没有办法在带有子像素消除锯齿的NSBitMapImageRep中绘制文字?文本是在不透明的白色背景上绘制的,我尝试使用CGContextSetShouldSmoothFonts函数,但这似乎没有帮助。

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];

当我使用NSImage-[NSImage lockFocus]中绘图时,我可以使文字平滑工作,但在Retina显示屏上运行时,这是不可靠的。

1 个答案:

答案 0 :(得分:2)

我最终使用这个替代代码来获得文本平滑:

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);