【问题标题】:Showing text with CGContextShowTextAtPoint draws strange text使用 CGContextShowTextAtPoint 显示文本会绘制奇怪的文本
【发布时间】:2013-02-05 21:50:25
【问题描述】:

我只是想在 UIImage 中叠加一个文本(使用 CGContext),但它没有显示我指定的文本。在这段代码中,我作为文本参数给出"Hello",但它显示“eÉääc”。我不知道发生了什么我认为角色被取代了,但我不知道如何解决它。 这是我的代码:

UIGraphicsBeginImageContextWithOptions(image.size, YES, 0);
CGContextRef c = UIGraphicsGetCurrentContext();
[image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
CGContextSetTextMatrix(c, CGAffineTransformMake(1.0, 0, 0, -1.0, 0, 0));
CGContextSelectFont(c, "ArialMT", 50, kCGEncodingFontSpecific);
CGContextSetRGBStrokeColor(c, 255, 0, 0, 1);
CGContextSetRGBFillColor(c, 255, 0, 0, 1);
CGContextSetCharacterSpacing(c, 2);
CGContextShowTextAtPoint(c,100,100, "Hello", 5);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

我正在使用西班牙语键盘(我不知道这是否重要),而 iPad(我正在测试应用程序的地方)是加泰罗尼亚语。

【问题讨论】:

    标签: ios xcode text sdk cgcontext


    【解决方案1】:

    CGContextShowTextAtPoint() 根据CGContextSelectFont 指定的编码参数解释给定的文本。你选择了kCGEncodingFontSpecific,这是字体内置编码(不管是什么)。

    唯一的其他选择是kCGEncodingMacRoman:

    CGContextSelectFont(c, "ArialMT", 50, kCGEncodingMacRoman);
    

    那么您的文本应该可以正确显示,只要您只使用 ASCII 字符集中的字符。

    对于非 ASCII 字符,您必须将字符串转换为 MacRoman 编码,参见例如以https://stackoverflow.com/a/13743834/1187415 为例。

    请注意CGContextShowTextAtPoint 无法显示一般的 Unicode 字符串,甚至欧元 (€) 字符也有问题。 NSString 的drawAtPoint:withFont: 方法没有这些限制。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 2021-09-22
      相关资源
      最近更新 更多