如何解决稍微弯曲CATextLayer
尝试弯曲一些文本。我正在尝试修改Curve text on existing circle,但不能在圆的上下文中使用它,而只是在一条直线上进行,但是老实说,我不确定我是否完全了解该代码在做什么以进行修改
extension CALayer {
func drawCurvedString(text: NSAttributedString,angle: CGFloat,radius: CGFloat) {
var radAngle = angle.radians
let textSize = text.boundingRect(
with: CGSize(width: .max,height: .max),options: [.usesLineFragmentOrigin,.usesFontLeading],context: nil)
.integral
.size
let perimeter: CGFloat = 2 * .pi * radius
let textAngle: CGFloat = textSize.width / perimeter * 2 * .pi
var textRotation: CGFloat = 0
var textDirection: CGFloat = 0
if radAngle > CGFloat(10).radians,radAngle < CGFloat(170).radians {
// bottom string
textRotation = 0.5 * .pi
textDirection = -2 * .pi
radAngle += textAngle / 2
} else {
// top string
textRotation = 1.5 * .pi
textDirection = 2 * .pi
radAngle -= textAngle / 2
}
for c in 0..<text.length {
let letter = text.attributedSubstring(from: NSRange(c..<c+1))
let charSize = letter.boundingRect(
with: CGSize(width: .max,context: nil)
.integral
.size
let letterangle = (charSize.width / perimeter) * textDirection
let x = charSize.width * CGFloat(c)//radius * cos(radAngle + (letterangle / 2))
let y: CGFloat = 0//radius * sin(radAngle + (letterangle / 2))
print("x:\(x),y: \(y)")
let singleChar = drawText(
text: letter,frame: CGRect(
x: (self.frame.size.width / 2) - (charSize.width / 2) + x,y: (self.frame.size.height / 2) - (charSize.height / 2) + y,width: charSize.width,height: charSize.height))
self.addSublayer(singleChar)
singleChar.transform = CATransform3DMakeAffineTransform(CGAffineTransform(rotationAngle: radAngle - textRotation))
radAngle += letterangle
}
}
func drawText(text: NSAttributedString,frame: CGRect) -> CATextLayer {
let textLayer = CATextLayer()
textLayer.frame = frame
textLayer.string = text
textLayer.alignmentMode = CATextLayerAlignmentMode.center
textLayer.contentsScale = UIScreen.main.scale
return textLayer
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。