arserConfig) -> NSDictionary {
//设置字体
let fontName = config.fontName
let fontSize = config.fontSize
let fontRef = CTFontCreateWithName(fontName as CFString?, fontSize, nil)
//设置行间距
var lineSpace = config.lineSpace
let settings: [CTParagraphStyleSetting] = [CTParagraphStyleSetting(spec: CTParagraphStyleSpecifier.lineSpacingAdjustment, valueSize: MemoryLayout<CGFloat>.size, value: &lineSpace), CTParagraphStyleSetting(spec: CTParagraphStyleSpecifier.maximumLineSpacing, valueSize: MemoryLayout<CGFloat>.size, value: &lineSpace), CTParagraphStyleSetting(spec: CTParagraphStyleSpecifier.minimumLineSpacing, valueSize: MemoryLayout<CGFloat>.size, value: &lineSpace)]
let theParagaraphRef = CTParagraphStyleCreate(settings, 3)
//设置字体颜色
let textColor = config.textColor
let dict = NSMutableDictionary()
dict.setObject(fontRef, forKey: kCTFontAttributeName as! NSCopying)
dict.setObject(theParagaraphRef, forKey: kCTParagraphStyleAttributeName as! NSCopying)
dict.setObject(textColor.cgColor, forKey: kCTForegroundColorAttributeName as! NSCopying)
return dict
}
// MARK: ------获取数据源------
class func parserAttributedContent(_ content: NSAttributedString, config: CTFrameParserConfig) -> CoreTextData {
let frameSetter = CTFramesetterCreateWithAttributedString(content)
let restrictSize = CGSize(width: config.width, height: CGFloat(MAXFLOAT))
let coretextSize = CTFramesetterSuggestFrameSizeWithConstraints(frameSetter, CFRangeMake(0, 0), nil, restrictSize, nil)
let textHeight = coretextSize.height
let frame = self.createFrame(frameSetter, config: config, height: textHeight)
let data = CoreTextData(ctFrame: frame, height: textHeight)
return data
}
// MARK: ------创建frame------
class func createFrame(_ frameSetter: CTFramesetter, config: CTFrameParserConfig, height: CGFloat) -> CTFrame {
let path = CGMutablePath()
path.addRect(CGRect(x: 0, y: 0, width: config.width, height: height))
let frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil)
return frame
}
}
4.一个数据源,CoreTextData,负责提供显示类的所需数据。
class CoreTextData: NSObject {
var ctFrame: CTFrame?
var height:CGFloat = 0
init(ctFrame: CTFrame, height: CGFloat) {
self.ctFrame = ctFrame
self.height = height
}
}
此外,我们需要通过一个模板文件来自定义需要展示的文本的信息,参考如下:
[
{
"type": "txt",
"content": "This is a ",
"fontName": "default",
"fontSize": 0,
"color": "default"
},
{
"type": "txt",
"content": "simple attributeString ",
"fontName": "Snell Roundhand Bold",
"fontSize": 26,
"color": "0xe7292e"
},
{
"type": "txt",
"content": "demo, ",
"fontName": "PingFangSC-Light",
"fontSize": 18,
"color": "0xf9f9f9"
},
{
"type": "txt",
"content": "you can use it ",
"fontName": "PingFangSC-Bold",
"fontSize": 13,
"color": "0x85d64d"
},
{
"type": "txt",
"content": "by adding a json tem |