`
jiapumin
  • 浏览: 341250 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

iOS上文本绘制的几种方法

 
阅读更多

文本绘制在开发客户端程序中是一个比较常用的功能,可分为采用控件和直接绘制两种方式。

采用控件的方式比较简便,添加一个比如UILabel对象,然后设置相关属性就好了。但这种方式局限性也比较大。

直接绘制相对比较自由,但也分为使用NSString和Quartz 2D两种方式。

NSString有一组绘制文本的函数,drawAtPoint是其中一个。使用方式如下:

1 NSString* text = @"This is English text(NSString).";
2 [text drawAtPoint:CGPointMake(0, 0) withFont:[UIFont systemFontOfSize:20]];

接口还是比较简单的,也可以画中文。

1 text = @"这是中文文本(NSString)。";
2 [text drawAtPoint:CGPointMake(0, 50) withFont:[UIFont systemFontOfSize:20]];

Quartz 2D中文本绘制稍微复杂一点,因为它提供的接口是C形式的,而不是OC的。先来看看如何画英文:

1 CGContextSetTextMatrix(context, CGAffineTransformMakeScale(1.0, -1.0));
2 CGContextSelectFont(context, "Helvetica", 20, kCGEncodingMacRoman);
3 const char* str = "This is English text(Quartz 2D).";
4 CGContextShowTextAtPoint(context, 0, 100, str, strlen(str));

CGContextSetTextMatrix是调整坐标系,防止文字倒立。
我们用同样的方法尝试绘制中文。

1 const char* str1 = "这是中文文本(Quartz 2D)。";
2 CGContextShowTextAtPoint(context, 0, 150, str1, strlen(str1));

但屏幕上显示的是乱码。为什么呢?

Quartz 2D Programming Guide中有这样一段说明:

To set the font to a text encoding other than MacRoman, you can use the functions CGContextSetFont and CGContextSetFontSize. You must supply a CGFont object to the function CGContextSetFont. You call the function CGFontCreateWithPlatformFont to obtain a CGFont object from an ATS font. When you are ready to draw the text, you use the function CGContextShowGlyphsAtPoint rather than CGContextShowTextAtPoint.

人家说了,如果编码超出MacRoman的范围,你要使用CGContextShowGlyphsAtPoint来绘制。这个函数和CGContextShowTextAtPoint类似,也是5个参数,而且只有第四个参数不同,是字形数组(可能描述的不准确)CGGlyph glyphs[],这个东西如何得到呢?在CoreText frameork(support iOS3.2 and later)提供了这样的接口。代码如下:

复制代码
 1 UniChar *characters;
 2 CGGlyph *glyphs;
 3 CFIndex count;
 4     
 5 CTFontRef ctFont = CTFontCreateWithName(CFSTR("STHeitiSC-Light"), 20.0, NULL);
 6 CTFontDescriptorRef ctFontDesRef = CTFontCopyFontDescriptor(ctFont);
 7 CGFontRef cgFont = CTFontCopyGraphicsFont(ctFont,&ctFontDesRef ); 
 8 CGContextSetFont(context, cgFont);
 9 CFNumberRef pointSizeRef = (CFNumberRef)CTFontDescriptorCopyAttribute(ctFontDesRef,kCTFontSizeAttribute);
10 CGFloat fontSize;
11 CFNumberGetValue(pointSizeRef, kCFNumberCGFloatType,&fontSize);
12 CGContextSetFontSize(context, fontSize);
13 NSString* str2 = @"这是中文文本(Quartz 2D)。";
14 count = CFStringGetLength((CFStringRef)str2);
15 characters = (UniChar *)malloc(sizeof(UniChar) * count);
16 glyphs = (CGGlyph *)malloc(sizeof(CGGlyph) * count);
17 CFStringGetCharacters((CFStringRef)str2, CFRangeMake(0, count), characters);
18 CTFontGetGlyphsForCharacters(ctFont, characters, glyphs, count);
19 CGContextShowGlyphsAtPoint(context, 0, 200, glyphs, str2.length);
20     
21 free(characters);
22 free(glyphs);
复制代码

STHeitiSC-Light是系统自带的一种中文字体。

这样写的话中文就能正常绘制出来了。

下图是显示效果,分别对应上面的5个示例。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics