人。 我做了富文本eidtor与Core Text的一些工作。我想保持固定的行高,它可以用以下代码完成:
NSMutableAttributedString *_attributedText = [[NSMutableAttributedString alloc]initWithAttributedString:_attributedString] ;
CGFloat lineSpace=20;
CTParagraphStyleSetting lineSpaceStyle;
lineSpaceStyle.spec=kCTParagraphStyleSpecifierMaximumLineHeight;
lineSpaceStyle.valueSize=sizeof(lineSpace);
lineSpaceStyle.value=&lineSpace;
//CTLineBreakMode lineBreakMode = kCTLineBreakByCharWrapping;
CTParagraphStyleSetting settings[]={
lineSpaceStyle,
// {.spec = kCTParagraphStyleSpecifierLineBreakMode, .valueSize = sizeof(CTLineBreakMode), .value = (const void*)&lineBreakMode},
};
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(settings, sizeof(settings));
[_attributedText addAttribute:(id)kCTParagraphStyleAttributeName value:(id)paragraphStyle range:NSMakeRange(0, _attributedText.mutableString.length)];
_attributedString = [_attributedText copy];
[_attributedText release];
_attributedText = nil;
CFRelease(paragraphStyle);
然后我想在其中插入一个图像。我想在图像上键入一些文字,代码如下:
CTRunDelegateCallbacks callbacks = {
.version = kCTRunDelegateVersion1,
.dealloc = AttachmentRunDelegateDealloc,
.getAscent = AttachmentRunDelegateGetAscent,
.getDescent = AttachmentRunDelegateGetDescent,
.getWidth = AttachmentRunDelegateGetWidth
};
CTRunDelegateRef Rundelegate = CTRunDelegateCreate(&callbacks, [image retain]); //3
NSMutableDictionary *attrDictionaryDelegate = [NSMutableDictionary dictionaryWithDictionary:self.defaultAttributes];
[attrDictionaryDelegate setObject:image
forKey:EGOTextAttachmentAttributeName];
[attrDictionaryDelegate setObject:(id)Rundelegate
forKey:(NSString*)kCTRunDelegateAttributeName];
[attrDictionaryDelegate setObject:fulltext
forKey:EGOTextAttachmentOriginStringKey];
NSAttributedString *newString = [[NSAttributedString alloc] initWithString:EGOTextAttachmentPlaceholderString
attributes:attrDictionaryDelegate];
[attrString replaceCharactersInRange:[result resultByAdjustingRangesWithOffset:attrString.length-astring.length].range
withAttributedString:newString];
换句话说,有没有办法让图片上的文字布局用Core Text ????? 任何人????
答案 0 :(得分:1)
非常简单
使用 CoreText 保持固定的行高,
让图片上的文字排版 image.draw(in: frame)
,
可能是用 CoreText
计算的帧。
这里是一个例子,在行中的第一个单词下面放一张背景图片
// here is set up
guard let ctx = UIGraphicsGetCurrentContext(), let f = frameRef else{
return
}
let xHigh = bounds.size.height
ctx.textMatrix = CGAffineTransform.identity
ctx.translateBy(x: 0, y: xHigh)
ctx.scaleBy(x: 1.0, y: -1.0)
guard let lines = CTFrameGetLines(f) as? [CTLine] else{
return
}
// here is an image
let bgGrip = UIImage(named: "grip")
if let pieces = CTLineGetGlyphRuns(line) as? [CTRun]{
let pieceCnt = pieces.count
for i in 0..<pieceCnt{
var p = lineOrigin
if i == 0{
var frame = imageFrame
frame.origin.y = lineOrigin.y + lineAscent - imageHeight + TextContentConst.offsetP.y
bgGrip?.draw(in: frame)
p.x += offsetX
}
ctx.textPosition = p
CTRunDraw(pieces[i], ctx, CFRange(location: 0, length: 0))
}
}