问题描述
我正在寻找一种方法来将一段文字转换为Cocoa中的图像。一切似乎都描述将图片转换为文字,而不是文字转换为图片。
I'm looking for a way to convert a piece of text to an image in Cocoa. Everything seems to describe converting an image to text not text to an image.
简单地说,我想要一个字(如Kevin转换为位图图像以操作并另存为JPEG。
Simply put, I would like to take a word (such as "Kevin") and convert it into a bitmap image to manipulate and save as a JPEG.
提供答案的人非常棒。谢谢你的三个不同的,同样有效的方法来做到这一点(是的,我测试了他们)。非常酷我希望我能给你所有正确的答案。
The people giving answers are awesome. Thank you for three different and equally valid ways to do it(yes i've tested them)....Very cool I wish I could give you all correct answers.
推荐答案
编辑:我误解了这个问题,并假设你想要Cocoa-touch代码(我已经离开它,以防万一你)。这里有一种方法在Cocoa使用CoreText(另一个海报说有很多方法):
I misread the question and assumed you wanted Cocoa-touch code (I've left it at the end in case you did). Here is one way of doing it in Cocoa using CoreText (as another poster says there are a bunch of ways):
{
NSString* string = @"Kevin";
CGFloat fontSize = 12.0f;
// Create an attributed string with string and font information
CTFontRef font = CTFontCreateWithName(CFSTR("Helvetica Light"), fontSize, nil);
NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys:
(id)font, kCTFontAttributeName,
nil];
NSAttributedString* as = [[NSAttributedString alloc] initWithString:string attributes:attributes];
CFRelease(font);
// Figure out how big an image we need
CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)as);
CGFloat ascent, descent, leading;
double fWidth = CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
// On iOS 4.0 and Mac OS X v10.6 you can pass null for data
size_t width = (size_t)ceilf(fWidth);
size_t height = (size_t)ceilf(ascent + descent);
void* data = malloc(width*height*4);
// Create the context and fill it with white background
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast;
CGContextRef ctx = CGBitmapContextCreate(data, width, height, 8, width*4, space, bitmapInfo);
CGColorSpaceRelease(space);
CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0, 1.0); // white background
CGContextFillRect(ctx, CGRectMake(0.0, 0.0, width, height));
// Draw the text
CGFloat x = 0.0;
CGFloat y = descent;
CGContextSetTextPosition(ctx, x, y);
CTLineDraw(line, ctx);
CFRelease(line);
// Save as JPEG
CGImageRef imageRef = CGBitmapContextCreateImage(ctx);
NSBitmapImageRep* imageRep = [[NSBitmapImageRep alloc] initWithCGImage:imageRef];
NSAssert(imageRep, @"imageRep must not be nil");
NSData* imageData = [imageRep representationUsingType:NSJPEGFileType properties:nil];
NSString* fileName = [NSString stringWithFormat:@"Kevin.jpg"];
NSString* fileDirectory = NSHomeDirectory();
NSString* filePath = [fileDirectory stringByAppendingPathComponent:fileName];
[imageData writeToFile:filePath atomically:YES];
// Clean up
[imageRep release];
CGImageRelease(imageRef);
free(data);
}
这是可可触式版本:
// Figure out the dimensions of the string in a given font.
NSString* kevin = @"Kevin";
UIFont* font = [UIFont systemFontOfSize:12.0f];
CGSize size = [kevin sizeWithFont:font];
// Create a bitmap context into which the text will be rendered.
UIGraphicsBeginImageContext(size);
// Render the text
[kevin drawAtPoint:CGPointMake(0.0, 0.0) withFont:font];
// Retrieve the image
UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
// Convert to JPEG
NSData* data = UIImageJPEGRepresentation(image, 1.0);
// Figure out a safe path
NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *docDir = [arrayPaths objectAtIndex:0];
// Write the file
NSString *filePath = [docDir stringByAppendingPathComponent:@"Kevin.jpg"];
BOOL success = [data writeToFile:filePath atomically:YES];
if(!success)
{
NSLog(@"Failed to write to file. Perhaps it already exists?");
}
else
{
NSLog(@"JPEG file successfully written to %@", filePath);
}
// Clean up
UIGraphicsEndImageContext();
当我开始iOS编程时,我发现了以下非直觉或不寻常的事情。测量和绘制字符串的方法是 NSString
上的方法(而不是像其他系统中的图形上下文)。保存数据的方法是 NSData
上的方法,而不是文件类!创建图形上下文的函数是纯C函数,不是任何类的一部分。
When I made started iOS programming I found the following things unintuitive or unusual. The methods to measure and draw strings are methods on NSString
(not the graphics context as in other systems). The method to save the data is a method on NSData
not a file class! The functions to create the graphics context are plain C functions and not part of any class.
希望这有助于!
这篇关于如何在Cocoa Objective-C中将文本转换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!