简体   繁体   中英

Drawing strings in iPhone

I am using below method to draw string.

-(void) drawRect:(CGRect)rect
{
    NSString *mName = @"Hi what are you doing";
    [mName drawInRect:CGRectMake(0,0,100,12) withFont:[UIFont boldSystemFontOfSize:12] lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentCenter]
}

Is it possible to draw to "Hi" in different font, "what" in different font in iPhone.

Use the method drawAtPoint:withFont: for drawing of each word. You must compute the position of each drawn string. This can be done with sizeWithFont: -method. For example:

NSString* firstString = @"Hi ";
NSString* secondString = @"what";
// where to draw
CGPoint position = CGPointMake(0, 0); 
CGFloat offset = [firstString sizeWithFont:font1].width + kSpaceBetweenWords;
// draw "Hi" with font1
[firstString drawAtPoint:position withFont:font1]; 
// draw "what" with font2
[secondString drawAtPoint:CGPointMake(position.x+offset, position.y) withFont:font2]; 

No, you need to do two draw requests - one for each font - but that is rather trivial.

What is not trivial is to know where to place the text if the text is dynamic. In that case I would recommend subclassing UIView and the drawRect method and just draw it yourself.

NSAttributedString is available for iOS 3.2 later. you can try this. Or else core text library is there to achieve the same...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM