有没有办法在UITextView中提供这种效果?如果不是,我怎样才能达到这个效果呢?

发布于 2013-01-23 07:24:10
出于同样的需求,我创建了一个UIView子类,用于绘制带有下沉大写的文本。文本是使用核心文本绘制的,正如@CodaFi建议的那样,在单独的核心文本框架中绘制首字下沉。
类的完整实现:https://gist.github.com/4596476
它的核心看起来像这样:
- (void)drawRect:(CGRect)rect {
// Create attributed strings
NSAttributedString *bodyText = [[NSAttributedString alloc] initWithString:[self.text substringWithRange:NSMakeRange(1, self.text.length -1)] attributes:_bodyAttributes];
NSAttributedString *capText = [[NSAttributedString alloc] initWithString:[[self.text substringWithRange:NSMakeRange(0, 1)] uppercaseString] attributes:_capAttributes];
CGRect capFrame = CGRectMake(0, 0, [capText size].width, [capText size].height);
// Set up graphics context
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
// Create type frames
CGMutablePathRef bodyPath = CGPathCreateMutable();
CGAffineTransform transform = CGAffineTransformTranslate(CGAffineTransformMakeScale(1, -1), 0, -self.bounds.size.height);
CGPathMoveToPoint(bodyPath, &transform, CGRectGetMaxX(capFrame), 0);
CGPathAddLineToPoint(bodyPath, &transform, self.bounds.size.width, 0);
CGPathAddLineToPoint(bodyPath, &transform, self.bounds.size.width, self.bounds.size.height);
CGPathAddLineToPoint(bodyPath, &transform, 0, self.bounds.size.height);
CGPathAddLineToPoint(bodyPath, &transform, 0, CGRectGetMaxY(capFrame));
CGPathAddLineToPoint(bodyPath, &transform, CGRectGetMaxX(capFrame), CGRectGetMaxY(capFrame));
CGPathCloseSubpath(bodyPath);
CGMutablePathRef capPath = CGPathCreateMutable();
CGPathAddRect(capPath, &transform, CGRectMake(0, 0, capFrame.size.width+10, capFrame.size.height+10));
// Draw text
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef) bodyText);
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), bodyPath, NULL);
CFRelease(framesetter);
CTFrameDraw(frame, context);
CFRelease(frame);
framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)capText);
frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), capPath, NULL);
CFRelease(framesetter);
CTFrameDraw(frame, context);
CFRelease(frame);
}它的要点是您创建了两个路径,一个矩形包含首字下沉,另一个矩形去除了其余文本的缺口。gist上的完整实现允许您使用属性控制字体、首字下沉周围的间距以及整个视图的内容嵌入。
它没有实现UITextView的大多数功能(只实现了我需要的功能),所以它可能不是一个完整的解决方案。
希望这能有所帮助!
https://stackoverflow.com/questions/11289552
复制相似问题