[英]How to center image in attributed string?
我有一張image
,我想與一堆文本一起居中,但即使我將NSMutableParagraphStyle
alignment
設置為center
,帶有圖片的行也不會居中
如果有人可以幫助我將圖像(即第一行)居中,那就太好了!
let text = " text next to image is not centered \n\n centered text \n more centered text"
let iconAttachment = textAttachment(fontSize: 14, image: #imageLiteral(resourceName: "icon"))
let iconString = NSAttributedString(attachment: iconAttachment)
let style = NSMutableParagraphStyle()
style.alignment = .center
style.minimumLineHeight = 20
let attributedText = NSMutableAttributedString()
attributedText.append(iconString)
let fullText = NSAttributedString(string: text, attributes: [NSParagraphStyleAttributeName : style])
attributedText.append(fullText)
private func textAttachment(fontSize: CGFloat, image: UIImage) -> NSTextAttachment {
let font = UIFont.systemFont(ofSize: fontSize) //set accordingly to your font, you might pass it in the function
let textAttachment = NSTextAttachment()
textAttachment.image = image
let mid = font.descender + font.capHeight
textAttachment.bounds = CGRect(x: 0, y: font.descender - image.size.height / 2 + mid + 2, width: image.size.width, height: image.size.height).integral
return textAttachment
}
這是在中心實現願望圖像的代碼。
let text = "\ntext next to image is not centered \n\n centered text \n more centered text"
let iconAttachment = textAttachment(fontSize: 5, image: #imageLiteral(resourceName: "eye"))
let iconString = NSAttributedString(attachment: iconAttachment)
let style = NSMutableParagraphStyle()
style.alignment = .center
style.minimumLineHeight = 20
let attributedText = NSMutableAttributedString()
attributedText.append(iconString)
let fullText = NSAttributedString(string: text, attributes: [NSParagraphStyleAttributeName : style])
attributedText.append(fullText)
lbl.attributedText = attributedText;
lbl.numberOfLines = 0
lbl.lineBreakMode = .byWordWrapping
lbl.textAlignment = .center
Output
注:function無變化
你應該使用.baselineOffset。 根據您的字體大小,offSet 會有所不同。
let image = NSImage(imageLiteralResourceName: "snail")
let attachment = NSTextAttachment()
attachment.image = image
let mutableAttributedString = NSMutableAttributedString(attachment: attachment)
mutableAttributedString.addAttributes([.baselineOffset : -2], range: NSRange(location: 0, length: mutableAttributedString.length))
mutableAttributedString.append(NSAttributedString(string: " Hello World!"))
label.attributedStringValue = mutableAttributedString
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.