Set color CFAttributedStringRef - ios

I have this methods for draw a table ant populated . What i want is to change the color for one word from each column , but i dont know how can i do it . Can somebeday help me ,please ? Any help will be appreciate .
in my app the user can select some attributes from segmente control... I want to export what he chosen in a pdf , like a table .So on each line a word will be selected
-(void)drawTableDataAt:(CGPoint)origin
withRowHeight:(int)rowHeight
andColumnWidth:(int)columnWidth
andRowCount:(int)numberOfRows
andColumnCount:(int)numberOfColumns
{
int padding = 1;
NSArray* headers = [NSArray arrayWithObjects:#"Grand", #"Taile ok", #"Petit", nil];
NSArray* invoiceInfo1 = [NSArray arrayWithObjects:#"Extra", #"Bon", #"Ordi", nil];
NSArray* invoiceInfo2 = [NSArray arrayWithObjects:#"Gras", #"Etat", #"Maigre", nil];
NSArray* invoiceInfo3 = [NSArray arrayWithObjects:#"Cru", #"Propre", #"Sale", nil];
NSArray* invoiceInfo4 = [NSArray arrayWithObjects:#"PLourd", #"PMoyen", #"PLeger", nil];
NSArray* invoiceInfo5 = [NSArray arrayWithObjects:#"CSup", #"CEgal", #"CInf", nil];
NSArray* allInfo = [NSArray arrayWithObjects:headers, invoiceInfo1, invoiceInfo2, invoiceInfo3, invoiceInfo4, invoiceInfo5,nil];
for(int i = 0; i < [allInfo count]; i++)
{
NSArray* infoToDraw = [allInfo objectAtIndex:i];
for (int j = 0; j < numberOfColumns; j++)
{
int newOriginX = origin.x + (j*columnWidth);
int newOriginY = origin.y + ((i+1)*rowHeight);
CGRect frame = CGRectMake(newOriginX + padding, newOriginY + padding, columnWidth, rowHeight);
[self drawText:[infoToDraw objectAtIndex:j] inFrame:frame];
}
}
}
-(void)drawText:(NSString*)textToDraw inFrame:(CGRect)frameRect
{
CFStringRef stringRef = (__bridge CFStringRef)textToDraw;
// Prepare the text using a Core Text Framesetter
CFAttributedStringRef currentText = CFAttributedStringCreate(NULL, stringRef, NULL);
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(currentText);
CGMutablePathRef framePath = CGPathCreateMutable();
CGPathAddRect(framePath, NULL, frameRect);
// Get the frame that will do the rendering.
CFRange currentRange = CFRangeMake(0, 0);
CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
CGPathRelease(framePath);
// Get the graphics context.
CGContextRef currentContext = UIGraphicsGetCurrentContext();
// Put the text matrix into a known state. This ensures
// that no old scaling factors are left in place.
CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);
// Core Text draws from the bottom-left corner up, so flip
// the current transform prior to drawing.
CGContextTranslateCTM(currentContext, 0, frameRect.origin.y*2);
CGContextScaleCTM(currentContext, 1.0, -1.0);
// Draw the frame.
CTFrameDraw(frameRef, currentContext);
CGContextScaleCTM(currentContext, 1.0, -1.0);
CGContextTranslateCTM(currentContext, 0, (-1)*frameRect.origin.y*2);
CFRelease(frameRef);
CFRelease(stringRef);
CFRelease(framesetter);
}

Based on the comments on the question, you mentioned that the words will never change. You could potentially create a whole bunch of if/else statements checking every word selected against every word in an array. I have put this down as a more efficient alternative and it should hopefully work. It may need some tweaking or even a loop to go through your chosen words, but this should hopefully put you in the right direction:
//declare your textToDraw as a new NSString
NSString *str = textToDraw;
//Make an Array of the str by adding objects that are separated by whitespace
NSArray *words = [str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//create a BOOL to check if your selected word exists in the array
BOOL wordExists = [words containsObject: #"%#", yourSelectedWord];
CTFramesetterRef framesetter = null;
//if the word exists, make it red
if(wordExists){
NSUInteger indexOfTheString = [words indexOfObject: #"%#", yourSelectedWord];
CFAttributedStringRef currentText = CFAttributedStringCreate(NULL,str, NULL);
[currentText addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:NSMakeRange(indexOfTheString, yourSelectedWord.length)];
framesetter = CTFramesetterCreateWithAttributedString(currentText);
}
This will match your selected word found against the right word in your array and highlight it red.

Related

Can't Create PDF and PRINT more than 60 Pages ( memory Raises & crashes) [duplicate]

This question already has answers here:
Cannot create PDF document with 400+ pages on iOS
(4 answers)
Closed 6 years ago.
I need to generate PDF more than 60 pages and need to Print it, but in iPhone & iPad memory Ram raises to 350.50MB-500.00MB and Crashes .
For Reducing memory->Running in dispatch queues also that doesn't help
Can't find the solution for this . Plz help me in this ...
and referred below link but doesn't help
Cannot create PDF document with 400+ pages on iOS
-(NSData*)getPdfFullLineSheetiPhone:(UIScrollView *)tableView GridCount:(NSInteger)count{
// -- first page height, rest pages height: adjust to get it right
#define FIRST_PAGE_HEIGHT_FULLSON 1040
#define REST_PAGES_HEIGHT_FULLSON 1090//1420
#define WIDTH_FULLSO_PORTRAITN 400
CGSize fittedSize;
CGRect priorBounds = tableView.frame;
// - the '200' is the cell height for estimating how many pages, and 200/3 is ROw calculation(How many rows in GMGridView)
fittedSize =CGSizeMake(WIDTH_FULLSO_PORTRAITN, count * 200/3);
tableView.bounds = CGRectMake(0, 0, fittedSize.width, fittedSize.height);
Generating Pages Code Starts
CGRect pdfPageBounds;
// Standard US Letter dimensions 8.5" x 11"
pdfPageBounds = CGRectMake(0, 0, 768/1.8, REST_PAGES_HEIGHT_FULLSON/1.79);
NSMutableData *pdfData = [[NSMutableData alloc] init];
UIGraphicsBeginPDFContextToData(pdfData, pdfPageBounds, nil);
int pageno=0;
{
// do page1
CGRect pdfPageBoundsPage1;
pdfPageBoundsPage1 = CGRectMake(0,0,768/1.8, FIRST_PAGE_HEIGHT_FULLSON/1.7);
UIGraphicsBeginPDFPageWithInfo(pdfPageBoundsPage1, nil);
{
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 10, 0);
[tableView.layer renderInContext:UIGraphicsGetCurrentContext()];
pageno ++;
}
//Rest of Pages
for (CGFloat pageOriginY = FIRST_PAGE_HEIGHT_FULLSON/1.7; pageOriginY < fittedSize.height; pageOriginY += REST_PAGES_HEIGHT_FULLSON/1.79)
{
#autoreleasepool {
UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil);
{
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 10, -pageOriginY);
[tableView.layer renderInContext:UIGraphicsGetCurrentContext()];
pageno ++;
}
}
}
}
UIGraphicsEndPDFContext();
tableView.bounds = priorBounds;
return pdfData;
}
Memory Raises in iPad4 whereas in iPad Mini 180-240MB nd crashes
you have to construct your code some thing like this:
UIGraphicsBeginPDFContextToFile( pdfPath, CGRectZero, nil );// as per rMaddy
UIGraphicsBeginPDFPageWithInfo();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
[tableView.layer renderInContext:pdfContext];
UIGraphicsEndPDFContext();
here:
file namecan be like this:
NSString *newPDFName = [NSString stringWithFormat:#”%#.pdf”, #"whatEverNameYouWant"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:newPDFName];
NSLog(#”%#”,pdfPath);
basically the main benefit of this approach will be reduce NSData which is creating memory pressure.
over all code will look some thing this:
// Set up we the pdf we're going to be generating is
UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil);
int i = 0;
for ( ; i < pages; i++)
{
#autoreleasepool{
// Specify the size of the pdf page
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, kDefaultPageWidth, kDefaultPageHeight), nil);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
// Move the context for the margins
CGContextTranslateCTM(currentContext, kMargin, kMargin);
// draw the layer to the pdf, ignore the "renderInContext not found" warning.
[tableView.layer.layer renderInContext:currentContext];
}
}
// all done with making the pdf
UIGraphicsEndPDFContext();
Thats it !! you can take care of your calculation
It is not the answer for above question , it is another Code which was tried for to generate PDf using
UIGraphicsBeginPDFPageWithInfo. This approach also crashes for more than 500 rows nothing but it comes around 56 Pages
After this approach after returning PDF Data when i assign that PDF Data to UIPrinterInteractionController Action -
It shows , SO i am unable to calculate Pages
Print-Job failed: Printer exists.
2016-05-27 00:37:26.131 APPName[9078:2952235] \032Send\032to\032Mac\032#\032macminiB._ipp._tcp.local.: startJob not called.
Note :
whereas this Printer error doesn't shows in Above code which i posted above with UIGraphicsBeginPDFContextToData
-(NSData *)getPdfSimpleSOTr:(UITableView *)tableView{
#define FIRST_PAGE_HEIGHT 1188
#define REST_PAGES_HEIGHT 1176.5
CGSize fittedSize;
CGRect priorBounds;
// 140208 dan - Comment: save the WIDTH
CGRect savedFrame = tableView.frame;
// 140207 dan - force portrait width
priorBounds = tableView.frame;
priorBounds.size.width=768; // put into Portrait
tableView.frame = priorBounds;
fittedSize = [tableView sizeThatFits:CGSizeMake(priorBounds.size.width, ([tableView numberOfRowsInSection:0] * 49) + 529)];
tableView.bounds = CGRectMake(0, 0, fittedSize.width, fittedSize.height);
CGRect pdfPageBounds;
pdfPageBounds = CGRectMake(0, -12, 768, REST_PAGES_HEIGHT);
File Name & Path
NSString *newPDFName = [NSString stringWithFormat:#"%#.pdf", #"AppName"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:newPDFName];
NSLog(#"%#",pdfPath);
Generating Pages
// Set up we the pdf we're going to be generating is
UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil);
int pageno=0;
{
CGRect pdfPageBoundsPage1 = CGRectMake(0,0,768, FIRST_PAGE_HEIGHT+15);//15
UIGraphicsBeginPDFPageWithInfo(pdfPageBoundsPage1, nil);
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 10, 0);
[tableView.layer renderInContext:context];
pageno ++;
}
for (CGFloat pageOriginY = FIRST_PAGE_HEIGHT; pageOriginY < fittedSize.height; pageOriginY += REST_PAGES_HEIGHT)
{
#autoreleasepool{
// Specify the size of the pdf page
UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil);
CGContextRef context = UIGraphicsGetCurrentContext();
// Move the context for the margins
CGContextTranslateCTM(context, 10, -pageOriginY);
// draw the layer to the pdf, ignore the "renderInContext not found" warning.
[tableView.layer renderInContext:context];
}
}
}
// all done with making the pdf
UIGraphicsEndPDFContext();
After GraphicsEnd retrieving NSData from FilePath
NSData *pdfData;
if([[NSFileManager defaultManager] fileExistsAtPath:pdfPath])
{
pdfData = [[NSFileManager defaultManager] contentsAtPath:pdfPath];
}
else
{
NSLog(#"File not exits");
}
tableView.bounds = priorBounds;
// 140208 dan - Comment: restored the saved WIDTH
tableView.frame=savedFrame ;
return pdfData;
}

C String in iOS looks blurry

I have been trying to render text in a arc . the text rendered as expected but it looks blurry. how can i fix this issue.
- (UIImage*) createMenuRingWithFrame:(CGRect)frame
{
NSArray* sections = [[NSArray alloc] initWithObjects:#"daily", #"yearly", #"monthly", #"weekly",nil];
CGRect imageSize = frame;
float perSectionDegrees = 360 / [sections count];
float totalRotation = 135;
float fontSize = ((frame.size.width/2) /2)/2;
self.menuItemsFont = [UIFont fontWithName:#"Avenir" size:fontSize];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, imageSize.size.width, imageSize.size.height, 8, 4 * imageSize.size.width, colorSpace,(CGBitmapInfo) kCGImageAlphaPremultipliedFirst);
CGPoint centerPoint = CGPointMake(imageSize.size.width / 2, imageSize.size.height / 2);
double radius = (frame.size.width / 2)-2;
for (int index = 0; index < [sections count]; index++)
{
BOOL textRotationDown = NO;
NSString* menuItemText = [sections objectAtIndex:index];
CGSize textSize = [menuItemText sizeWithAttributes:
#{NSFontAttributeName: self.menuItemsFont}];
char* menuItemTextChar = (char*)[menuItemText cStringUsingEncoding:NSASCIIStringEncoding];
if (totalRotation>200.0 && totalRotation <= 320.0) {
textRotationDown = YES;
}
else
textRotationDown= NO;
float x = centerPoint.x + radius * cos(DEGREES_TO_RADIANS(totalRotation));
float y = centerPoint.y + radius * sin(DEGREES_TO_RADIANS(totalRotation));
CGContextSaveGState(context);
CFStringRef font_name = CFStringCreateWithCString(NULL, "Avenir", kCFStringEncodingMacRoman);
CTFontRef font = CTFontCreateWithName(font_name, fontSize, NULL);
CFStringRef keys[] = { kCTFontAttributeName };
CFTypeRef values[] = { font };
CFDictionaryRef font_attributes = CFDictionaryCreate(kCFAllocatorDefault, (const void **)&keys, (const void **)&values, sizeof(keys) / sizeof(keys[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFRelease(font_name);
CFRelease(font);
CFStringRef string = CFStringCreateWithCString(NULL, menuItemTextChar, kCFStringEncodingMacRoman);
CFAttributedStringRef attr_string = CFAttributedStringCreate(NULL, string, font_attributes);
CTLineRef line = CTLineCreateWithAttributedString(attr_string);
CGContextTranslateCTM(context, x, y);
CGContextRotateCTM(context, DEGREES_TO_RADIANS(totalRotation - (textRotationDown?275:90)));
CGContextSetTextPosition(context,0 - (textSize.width / 2), 0 - (textSize.height / (textRotationDown?20:4)));
CTLineDraw(line, context);
CFRelease(line);
CFRelease(string);
CFRelease(attr_string);
CGContextRestoreGState(context);
totalRotation += perSectionDegrees;
}
CGImageRef contextImage = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return [UIImage imageWithCGImage:contextImage];
}
One problem is that you are not allowing for screen resolution. Make your bitmap context twice as big, or three times as big; multiply all the values appropriately (this is easiest if you just apply a scale CTM at the outset); and then at the end, instead of calling imageWithCGImage:, call imageWithCGImage:scale:orientation:, setting the corresponding scale.
If you had created your context with UIGraphicsBeginImageContextWithOptions, that would have happened automatically (if you had provided a third argument of zero), or you could explicitly have set the third argument to provide a scale for the context and hence the image derived from it. But by building your context manually, you threw away the capacity to provide it with a scale.

CoreText and right alignment

I'm writing a class to generate PDFs, I'll publish as I will finish it!
I'm unable to align text to the right, with the CTParagraphStyle, the text is always on the left. How does it is possible? What I'm getting wrong?
- (void)addText:(NSString *)text color:(UIColor *)color fontSize:(CGFloat)size floating:(BOOL)floating {
CGContextSaveGState(pdfContext);
// Prepare font
CTFontRef font = CTFontCreateWithName(CFSTR("Verdana"), size, NULL);
// Font color
CGColorRef fontColor = [color CGColor];
// Paragraph
CTTextAlignment alignment = kCTRightTextAlignment;
CTParagraphStyleSetting settings[] = {
{kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment}
};
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(settings, sizeof(settings) / sizeof(settings[0]));
// Create an attributed string
CFStringRef keys[] = { kCTFontAttributeName , kCTParagraphStyleAttributeName, kCTForegroundColorAttributeName};
CFTypeRef values[] = { font, paragraphStyle, fontColor};
CFDictionaryRef attr = CFDictionaryCreate(NULL, (const void **)&keys, (const void **)&values,
sizeof(keys) / sizeof(keys[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFAttributedStringRef attrString = CFAttributedStringCreate(NULL, (CFStringRef)text, attr);
CFRelease(paragraphStyle);
CFRelease(attr);
// Draw the string
CTLineRef line = CTLineCreateWithAttributedString(attrString);
CGContextSetTextPosition(pdfContext, xPadding, [self relativeHeight:currentHeight+size]);
CTLineDraw(line, pdfContext);
// Clean up
CFRelease(line);
CFRelease(attrString);
CFRelease(font);
CGContextRestoreGState(pdfContext);
if(floating == NO) {
currentHeight += size;
}
}
Remove CTLineDraw() and its related code and use CTFrameDraw().
Try this:
// Create the Core Text framesetter using the attributed string.
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attrString);
// Create the Core Text frame using our current view rect bounds.
UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.bounds];
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), [path CGPath], NULL);
CTFrameDraw(frame, pdfContext);

iOS - Generating pdf from multiple files

I am attempting to convert some text files into a pdf. Now the easiest thing in the world right now is to simply combine all of the text from the files into a single string and then use the iOS documentation here to render it into a single pdf. The trouble is, these are large text files; together they can equal well over 90 pages. Therefore I will need to add in some hyperlinks so I can create a table of contents at the top and the user can quickly move to the beginning of each text file rather than have to scroll through 60 pages to get to where they want to go.
Problem is, if I combine the txt files into a single string, I have no way of knowing when each file will end while it is paginating, therefore I wanted to add the files separately to the pdf before finally publishing it. Problem is, at best only the last txt file will show up rendered, most likely because it is overwriting the previous ones. Below is my code, any ideas?
- (void)savePDFFile:(NSString *)file_Name
{
// NSArray *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *homeDir = NSHomeDirectory();
NSString *saveDirectory = [NSString stringWithFormat: #"%#/%#", homeDir, #"Documents/"];
NSArray *fileAr = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:saveDirectory error:nil];
// NSString *text = #"";
// NSMutableArray *textArray = [[NSMutableArray alloc] init];
NSInteger currentPage = 0;
NSString *completeString = #"";
for (NSString *string in fileAr) {
if([string hasSuffix:#"txt"]){
NSString *file = [NSString stringWithFormat: #"%#/%#", saveDirectory, string];
NSString *text =[NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil];
completeString = [NSString stringWithFormat:#"%#%#", completeString, text];
}
}
for (NSString *string in fileAr) {
if([string hasSuffix:#"txt"]){
NSString *file = [NSString stringWithFormat: #"%#/%#", saveDirectory, string];
NSString *text =[NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil];
// Prepare the text using a Core Text Framesetter
CFAttributedStringRef currentText = CFAttributedStringCreate(NULL, (CFStringRef)text, NULL);
if (currentText) {
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)currentText);
// CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(currentText);
if (framesetter) {
NSString* pdfFileName = file_Name;
// Create the PDF context using the default page size of 612 x 792.
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
CFRange currentRange = CFRangeMake(0, 0);
BOOL done = NO;
do {
// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
// Draw a page number at the bottom of each page
currentPage++;
[self drawPageNumber:currentPage];
// Render the current page and update the current range to
// point to the beginning of the next page.
currentRange = [self renderPage:currentPage withTextRange:currentRange andFramesetter:framesetter];
// If we're at the end of the text, exit the loop.
if (currentRange.location == CFAttributedStringGetLength((CFAttributedStringRef)currentText))
done = YES;
} while (!done);
// Release the framewetter.
CFRelease(framesetter);
CFRelease(currentText);
}
}
// Close the PDF context and write the contents out.
UIGraphicsEndPDFContext();
} else {
NSLog(#"Could not create the framesetter needed to lay out the atrributed string.");
}
// Release the attributed string.
}
}
// Use Core Text to draw the text in a frame on the page.
- (CFRange)renderPage:(NSInteger)pageNum withTextRange:(CFRange)currentRange
andFramesetter:(CTFramesetterRef)framesetter
{
// Get the graphics context.
CGContextRef currentContext = UIGraphicsGetCurrentContext();
// Put the text matrix into a known state. This ensures
// that no old scaling factors are left in place.
CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);
// Create a path object to enclose the text. Use 72 point
// margins all around the text.
CGRect frameRect = CGRectMake(72, 72, 468, 648);
CGMutablePathRef framePath = CGPathCreateMutable();
CGPathAddRect(framePath, NULL, frameRect);
// Get the frame that will do the rendering.
// The currentRange variable specifies only the starting point. The framesetter
// lays out as much text as will fit into the frame.
CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
CGPathRelease(framePath);
// Core Text draws from the bottom-left corner up, so flip
// the current transform prior to drawing.
CGContextTranslateCTM(currentContext, 0, 792);
CGContextScaleCTM(currentContext, 1.0, -1.0);
// Draw the frame.
CTFrameDraw(frameRef, currentContext);
// Update the current range based on what was drawn.
currentRange = CTFrameGetVisibleStringRange(frameRef);
currentRange.location += currentRange.length;
currentRange.length = 0;
CFRelease(frameRef);
return currentRange;
}
I made progress and ran into another problem, so I asked an additional question here.
Eventually, with my own testing and a little bit of help, I solved the issue.

Issue with importing korean localization text into xcode

I am completing the final part of localizations for a project. The translated text has come back to me split between .txt and .docx formats.
The .txt once entered into the localizable.strings works fine, but that copied from word document doesn't work.
This is what I've tried so far:
save .docx as .txt and let word encode
save .txt as korean (Mac OS X),
then copy this text to XCode and reinterpret as korean (Mac OS X), then
convert to utf-16
Have tried many options to convert to utf-16, but just can't seem to crack it.
Any ideas would be much appreciated.
Here is the localized help view implementation:
helpText = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:
NSLocalizedString(#" The Actions Tab", nil), kHelpTextKeyString,
#"Arial", kHelpTextKeyFontName,
[NSNumber numberWithInt:20], kHelpTextKeyFontSize,
[[UIColor blackColor] CGColor], kHelpTextKeyColor,
CGRectCreateDictionaryRepresentation(CGRectMake(30.0, 55.0, 200.0, 28.0)), kHelpTextKeyRect,
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
[NSArray arrayWithObjects:
NSLocalizedString(#"
- (void)displaySelectedHelpImage:(UIImage *)orgImage withTextArray:(NSArray *)textArr {
CGImageRef cgImage = [orgImage CGImage];
int pixelsWide = CGImageGetWidth(cgImage);
int pixelsHigh = CGImageGetHeight(cgImage);
int bitsPerComponent = CGImageGetBitsPerComponent(cgImage);//8; // fixed
int bitsPerPixel = CGImageGetBitsPerPixel(cgImage);//bitsPerComponent * numberOfCompnent;
int bytesPerRow = CGImageGetBytesPerRow(cgImage);//(pixelsWide * bitsPerPixel) // 8; // bytes
int byteCount = (bytesPerRow * pixelsHigh);
CGColorSpaceRef colorSpace = CGImageGetColorSpace(cgImage);//CGColorSpaceCreateDeviceRGB();
// Allocate data
NSMutableData *data = [NSMutableData dataWithLength:byteCount];
// Create a bitmap context
CGContextRef context = CGBitmapContextCreate([data mutableBytes], pixelsWide, pixelsHigh, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast); //kCGImageAlphaPremultipliedLast);//kCGImageAlphaNoneSkipLast); //kCGImageAlphaOnly);
// Set the blend mode to copy to avoid any alteration of the source data or to invert to invert image
CGContextSetBlendMode(context, kCGBlendModeCopy);
// Set alpha
CGContextSetAlpha(context, 1.0);
// Color image
//CGContextSetRGBFillColor(context, 1 ,1, 1, 1.0);
//CGContextFillRect(context, CGRectMake(0.0, 0.0, pixelsWide, pixelsHigh));
// Draw the image to extract the alpha channel
CGContextDrawImage(context, CGRectMake(0.0, 0.0, pixelsWide, pixelsHigh), cgImage);
// add text to image
// Changes the origin of the user coordinate system in a context
//CGContextTranslateCTM (context, pixelsWide, pixelsHigh);
// Rotate context upright
//CGContextRotateCTM (context, -180. * M_PI/180);
for (NSDictionary *dic in textArr) {
CGContextSelectFont (context,
//todo
[[dic objectForKey:kHelpTextKeyFontName] UTF8String],
[[dic objectForKey:kHelpTextKeyFontSize] intValue],
kCGEncodingMacRoman);
CGContextSetCharacterSpacing (context, 2);
CGContextSetTextDrawingMode (context, kCGTextFillStroke);
CGColorRef color = (CGColorRef)[dic objectForKey:kHelpTextKeyColor];
CGRect rect;
CGRectMakeWithDictionaryRepresentation((CFDictionaryRef)[dic objectForKey:kHelpTextKeyRect], &rect);
CGContextSetFillColorWithColor(context, color);
CGContextSetStrokeColorWithColor(context, color);
if ([[dic objectForKey:kHelpTextKeyString] isKindOfClass:[NSArray class]]) {
for (NSString *str in [dic objectForKey:kHelpTextKeyString]) {
CGContextShowTextAtPoint(context,
rect.origin.x,
pixelsHigh - rect.origin.y,
[str cStringUsingEncoding:[NSString defaultCStringEncoding]],
[str length]);
rect.origin.y += [[dic objectForKey:kHelpTextKeyFontSize] intValue];
}
For anyone facing this issue, it was solved by using the coretext foundation class.
What do the Word documents contain? What do you mean by "doesn't work?"
If they contain strings, couldn't you simply append them to the existing localizable.strings file? Since that works there is no encoding issue in this file, you could just copy/paste them from Word into the localizable.strings file in XCode.

Resources