有没有办法在具有子像素抗锯齿功能的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 lockFocus]
绘制NSImage
时,我可以让文本平滑工作,但在 Retina 显示器上运行它时,这并不可靠。
我最终使用了这个替代代码来获得文本平滑:
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);