簡體   English   中英

如何在屬性字符串中居中圖像?

[英]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無變化

在此處輸入圖像描述

你只需要 Alignment 你的 lebel 文本居中,它就會起作用:

 label.textAlignment = .center

在此處輸入圖像描述

你應該使用.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM