如何解决Core Text使用Swift在iOS中计算字母和红宝石注释框架
如何在iOS中由CoreText和CoreGraphics呈现的CTFrame文本中,为每个红宝石注释字符(或假名)提供边界框? (iOS 11、12或13)
基于这个问题Core Text calculate letter frame in iOS,我制作了一个快速版本的程序,将每个字符都包围在一个红色框中,但我无法获得红宝石注释字符的边框, aka furigana 。出于这个问题的目的,我将红宝石字符框涂成绿色。
我该如何实现?有任何想法吗?
编辑:为清楚起见,绿色框是在插图软件中手工绘制的。我需要通过代码绘制绿色框。
完整源代码在GitHub https://github.com/huse360/LetterFrame中 这是主要的源代码:
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
context.textMatrix = .identity
context.translateBy(x: 0,y: self.bounds.size.height)
context.scaleBy(x: 1.0,y: -1.0)
let string = "|優勝《ゆうしょう》の|懸《か》かった|試合《しあい》。|Test《テスト》.\nThe quick brown fox jumps over the lazy dog. 12354567890 @#-+"
let attributedString = Utility.sharedInstance.furigana(String: string)
let range = attributedString.mutableString.range(of: attributedString.string)
attributedString.addAttribute(.font,value: font,range: range)
let framesetter = attributedString.framesetter()
let textBounds = self.bounds.insetBy(dx: 20,dy: 20)
let frame = framesetter.createFrame(textBounds)
//Draw the frame text:
frame.draw(in: context)
let origins = frame.lineOrigins()
let lines = frame.lines()
context.setStrokeColor(UIColor.red.cgColor)
context.setLineWidth(0.7)
for i in 0 ..< origins.count {
let line = lines[i]
for run in line.glyphRuns() {
let font = run.font
let glyphPositions = run.glyphPositions()
let glyphs = run.glyphs()
let glyphsBoundingRects = font.boundingRects(of: glyphs)
//DRAW the bounding box for each glyph:
for k in 0 ..< glyphPositions.count {
let point = glyphPositions[k]
let gRect = glyphsBoundingRects [k]
var box = gRect
box.origin += point + origins[i] + textBounds.origin
context.stroke(box)
}// for k
}//for run
}//for i
}//func draw
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。