I am using the body text API to draw text in the user interface. (I do not know other methods, because most of the Google search results lead me to the main body of the api).
I read several guides on the Internet about using the basic text API. In this tutorial, I see step by step the setting from the matrix, the attribute row in the framesetter ... but none of them thoroughly explains the meaning of each step, so I cannot change it myself.
Below is the code that displays the text on the screen with (x,y) - this is the place I want to draw. This piece of code clearly describes step by step, making a drawing on the screen. However, I do not know where to put the parameters x and y, so the text will begin to draw at that point in the rectangle.
// draw text on screen. + (void)drawText:(CGContextRef)context bound:(CGRect)rect text:(NSString *)text x:(float)xy:(float) y color:(UIColor *)color size:(float)textSize{ CGContextSaveGState(context); // always remember to reset the text matrix before drawing. // otherwise the result will be unpredictable like using uninitialize memory CGContextSetTextMatrix(context, CGAffineTransformIdentity); CGContextSetTextMatrix(context, CGAffineTransformMakeScale(1.0f, -1.0f)); // Flip the coordinate system. because core Text uses different coordinate system with UI Kit CGContextTranslateCTM(context, 0, rect.size.height); CGContextScaleCTM(context, 1.0, -1.0); // step 1: prepare attribute string NSDictionary *attributes; attributes = @{ (NSString *) kCTFontAttributeName : [UIFont fontWithName:@"Helvetica" size:textSize], (NSString *) kCTForegroundColorAttributeName : color }; NSAttributedString *str = [[NSAttributedString alloc] initWithString:text attributes:attributes]; CFAttributedStringRef attrString = (__bridge CFAttributedStringRef)str; // step 2: create CTFFrameSetter CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attrString); // step 3. create CGPath CGMutablePathRef path = CGPathCreateMutable(); CGPathAddRect(path, NULL, rect); // step 4. get the frame // use the CGPath and CTFrameSetter to create CTFrame. then drawn it in currently context CTFrameRef frame = CTFramesetterCreateFrame (framesetter, CFRangeMake(0, 0), path, NULL); CTFrameDraw(frame, context); // step 5. release resource //CFRelease(attrString); CFRelease(framesetter); CFRelease(frame); CFRelease(path); CGContextRestoreGState(context); }
Moreover, I see that there is a function: CGContextSetTextPosition It seems to me that I need, but where should I add the code above. I tried some, but it fails. Please tell me how to fix it.
Thanks:)
source share