2013-02-21 80 views
0

我试图绘制一个字符串drawAtPoint,而不是CGContextShowTextAtPoint用drawAtPoint定位字符串?

- (UIImage *)drawonimage:(UIImage *)img { 
// myString is a string to draw 
// fontName is a string (font name) 
// fontSize is the font size (CGfloat) 

CGFloat w = img.size.width; 
CGFloat h = img.size.height; 

UIGraphicsBeginImageContextWithOptions(img.size,NO,1.0f); 
CGColorSpaceRef colorSpace0 = CGColorSpaceCreateDeviceRGB(); 
CGContextRef context0 = CGBitmapContextCreate(NULL,w,h,8,4 * w,colorSpace0,kCGImageAlphaPremultipliedFirst); 
CGContextDrawImage(context0,CGRectMake(0,0,w,h),img.CGImage); 
CGPoint p0 = CGPointMake(0,0); 
[img drawAtPoint:p0]; 
CGPoint p1 = CGPointMake(0,0); 
UIColor *aColor; 
aColor = [UIColor colorWithRed:100/255.0 green:120.0/255.0 blue:140.0/255.0 alpha:90/100.0]; 
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(),aColor.CGColor); 
[myString drawAtPoint:p1 withFont:[UIFont fontWithName:fontName size:fontSize]]; 
UIImage *Img = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
return Img; 
} 

我的问题是字符串实际出现的位置。例如,让我假设我想绘制的字符串是“Hello world!”字符串的最左上角不在0,0处。 (见图)我想,外观取决于字体,字体大小和其他因素。所以我想知道是否有测量弦高(不是宽度)的方法? 或者我该怎么做才能使字符串的左上角(箭头处)位于0,0?

谢谢你的帮助。

enter image description here

回答

1

看来,是不平凡的... sizeWithFont总是返回最大可能值高度坚韧它返回宽度的正确值...

如这里指出(How do I calculate the exact height of text using UIKit? ),你需要看看CoreText框架(http://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/CoreText_Programming/Introduction/Introduction.html#//apple_ref/doc/uid/TP40005533)。

+0

谢谢。我还没有看到'我如何计算...'主题。 – 2013-02-21 15:17:45

+0

不客气! – apascual 2013-02-21 15:19:43