我试图在 UILabel 字符的特定部分后面绘制圆圈,而不必使用多个标签或重新计算框架。
我知道我可以使用属性文本将图像插入到 UILabel 中,但我希望圆圈位于数字后面(从 1 到 9)。我不想存储从 1 到 9 的图像。我也找不到任何 pod 可以实现此目的。
let fullText = NSMutableAttributedString()
let imageAttachment = NSTextAttachment()
imageAttachment.image = UIImage(named: "\(number)_\(color == .yellow ? "yellow" : "gray")")
let imageString = NSAttributedString(attachment: imageAttachment)
let endString = NSAttributedString("nouveaux")
fullString.append(imageString)
fullString.append(endString)
mainLabel.attributedText = fullString
Run Code Online (Sandbox Code Playgroud)
编辑
我想在字符串的每个数字后面画一个圆圈。如果可能的话,我希望它成为一个通用工具,如果可能的话,它是一种返回属性字符串的解析器,如果没有的话,它是一个唯一的 UIView。另一个用例是“4 条消息 | 聊天 2”(4 条是黄色,2 条是灰色)
我不明白为什么你不只使用实时绘制圆圈中的数字的实用函数。这样,您就可以拥有您喜欢的任何数字字体、圆圈大小、数字颜色和圆圈颜色。例如:
func circleAroundDigit(_ num:Int, circleColor:UIColor,
digitColor:UIColor, diameter:CGFloat,
font:UIFont) -> UIImage {
precondition((0...9).contains(num), "digit is not a digit")
let p = NSMutableParagraphStyle()
p.alignment = .center
let s = NSAttributedString(string: String(num), attributes:
[.font:font, .foregroundColor:digitColor, .paragraphStyle:p])
let r = UIGraphicsImageRenderer(size: CGSize(width:diameter, height:diameter))
return r.image {con in
circleColor.setFill()
con.cgContext.fillEllipse(in:
CGRect(x: 0, y: 0, width: diameter, height: diameter))
s.draw(in: CGRect(x: 0, y: diameter / 2 - font.lineHeight / 2,
width: diameter, height: diameter))
}
}
Run Code Online (Sandbox Code Playgroud)
使用方法如下:
let im = circleAroundDigit(3, circleColor: .yellow,
digitColor: .white, diameter: 30, font:UIFont(name: "GillSans", size: 20)!)
Run Code Online (Sandbox Code Playgroud)
这是生成的图像;但请注意,只需通过不同方式调用该函数即可调整此方法的各个方面:
好的,现在你已经有了一张图像。您说您已经知道如何将图像内联插入属性字符串并将其显示为标签的一部分,所以我不会解释如何做到这一点:
| 归档时间: |
|
| 查看次数: |
1133 次 |
| 最近记录: |