首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在UITextView中显示首字母过大的文本块

问在UITextView中显示首字母过大的文本块
EN

Stack Overflow用户
提问于 2012-07-02 15:43:42
回答 1查看 419关注 0票数 3

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

​

​

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-01-23 07:24:10

出于同样的需求,我创建了一个UIView子类,用于绘制带有下沉大写的文本。文本是使用核心文本绘制的,正如@CodaFi建议的那样,在单独的核心文本框架中绘制首字下沉。

类的完整实现:https://gist.github.com/4596476

它的核心看起来像这样:

代码语言:javascript
复制
- (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的大多数功能(只实现了我需要的功能),所以它可能不是一个完整的解决方案。

希望这能有所帮助!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11289552

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档