我有以下代码,我试图使用核心文本来绘制,这就是为什么我不能像 UILabel 那样剪辑文本。换句话说,我必须弄清楚我自己的省略号('...')。
CGSize commentSize = [[self.sizeDictionary_ valueForKey:commentSizeKey] CGSizeValue];
CGSize actualSize = [[self.sizeDictionary_ valueForKey:actualCommentSizeKey] CGSizeValue];
NSString *actualComment = self.highlightItem_.comment;
if (actualSize.height > commentSize.height){
actualComment = [self.highlightItem_.comment stringByReplacingCharactersInRange:NSMakeRange(68, 3) withString:@"..."];
}
我很难根据 CGSize 找到“...”的范围。解决这个问题的最佳方法是什么?
我是这样画的:
CFStringRef string = CFBridgingRetain(actualComment);
CFMutableAttributedStringRef comment = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
CFAttributedStringReplaceString (comment ,CFRangeMake(0, 0), string);
CGColorRef blue = CGColorRetain([UIColor colorWithRed:131/255.f green:204/255.f blue:253/255.f alpha:1.0].CGColor);
CGColorRef gray = CGColorRetain([UIColor colorWithWhite:165/255.f alpha:1.0].CGColor);
CFAttributedStringSetAttribute(comment, CFRangeMake(0, [name length]),kCTForegroundColorAttributeName, blue);
CFAttributedStringSetAttribute(comment, CFRangeMake([name length], [self.highlightItem_.comment length] - [name length]),kCTForegroundColorAttributeName, gray);
CGColorRelease (blue);
CGColorRelease (gray);
CTFontRef nameFont = CTFontCreateWithName(CFBridgingRetain(kProximaNovaBold), 13.0f, nil);
CFAttributedStringSetAttribute(comment,CFRangeMake(0, [name length]),kCTFontAttributeName,nameFont);
CTFontRef commentFont = CTFontCreateWithName(CFBridgingRetain(kProximaNovaRegular), 13.0f, nil);
CFAttributedStringSetAttribute(comment, CFRangeMake([name length], [self.highlightItem_.comment length] - [name length]),kCTFontAttributeName,commentFont);
CGFloat commentYOffset = floorf((self.commentHeight_ - commentSize.height)/2);
CGContextSaveGState(context);
CGRect captionFrame = CGRectMake(0, 0, rect.size.width - 80, commentSize.height);
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(comment);
CGMutablePathRef captionFramePath = CGPathCreateMutable();
CGPathAddRect(captionFramePath, NULL, captionFrame);
CTFrameRef mainCaptionFrame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), captionFramePath, NULL);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, self.buttonSize_ + 25, self.imageHeight_ + self.commentHeight_ + 6 - commentYOffset);
CGContextScaleCTM(context, 1.0, -1.0);
CTFrameDraw(mainCaptionFrame, context);
CGContextRestoreGState(context);