我有这段代码可以创建一个 CATextLayer 并将其绘制到 UIView 上:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
CGRect viewRect = CGRectMake(50.0f, 50.0f, 345.0f, 120.0f);
CATextLayer *textLayer = [CATextLayer layer];
textLayer.contentsScale = [[UIScreen mainScreen] scale];
textLayer.wrapped = YES;
textLayer.truncationMode = kCATruncationNone;
UIFont *font = [UIFont fontWithName:@"SnellRoundhand" size:20.0f];
textLayer.string = @"Lorem Lipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.";
textLayer.alignmentMode = kCAAlignmentLeft;
textLayer.fontSize = font.pointSize;
CTFontRef fontRef = CTFontCreateWithName((__bridge CFStringRef)font.fontName, font.pointSize, nil);
textLayer.font = fontRef;
CFRelease(fontRef);
textLayer.backgroundColor = [[UIColor lightGrayColor] CGColor];
textLayer.foregroundColor = [[UIColor blackColor] CGColor];
textLayer.frame = viewRect;
UIGraphicsBeginImageContextWithOptions(textLayer.frame.size, NO, 0);
[textLayer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *textImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *textImageView = [[UIImageView alloc] initWithImage:textImage];
textImageView.frame = viewRect;
[self.view addSubview:textImageView];
}
不幸的是,在渲染视图时,一些字符被截断了。在我发布的示例中,开头的“L”缺少最左边的像素,而第二个末尾的“d”缺少最右边的像素。
有没有办法在不改变文本包装方式的情况下防止这种中断发生?