使用drawAtPoint定位字符串?

时间:2013-02-21 14:42:18

标签: iphone ios objective-c ios6 uiimage

我正在尝试使用 drawAtPoint 绘制字符串,而不是使用 CGContextShowTextAtPoint

- (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 个答案:

答案 0 :(得分: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)。

相关问题