how to resize an image or done as a NSAttributedString NSTextAttachment (or set its initital size)

前端 未结 5 1884
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 08:24

I have a NSAttributedString to which I am adding a NSTextAttachment. The image is 50w by 50h but I\'d like it to scale down to reflect the line height of the attributed stri

5条回答
  •  醉酒成梦
    2020-11-30 09:06

    Swift4 if you want a attributed string along with the image or a icon

    here you can do something like this.

    func AttributedTextwithImgaeSuffixAndPrefix(AttributeImage1 : UIImage , AttributedText : String ,AttributeImage2 : UIImage,  LabelBound : UILabel) -> NSMutableAttributedString
    {
        let fullString = NSMutableAttributedString(string: "  ")
        let image1Attachment = NSTextAttachment()
        image1Attachment.bounds = CGRect(x: 0, y: ((LabelBound.font.capHeight) - AttributeImage1.size.height).rounded() / 2, width: AttributeImage1.size.width, height: AttributeImage1.size.height)
        image1Attachment.image = AttributeImage1
        let image1String = NSAttributedString(attachment: image1Attachment)
        let image2Attachment = NSTextAttachment()
        image2Attachment.bounds = CGRect(x: 0, y: ((LabelBound.font.capHeight) - AttributeImage2.size.height).rounded() / 2, width: AttributeImage2.size.width, height: AttributeImage2.size.height)
        image2Attachment.image = AttributeImage2
        let image2String = NSAttributedString(attachment: image2Attachment)
        fullString.append(image1String)
        fullString.append(NSAttributedString(string: AttributedText))
        fullString.append(image2String)
        return fullString
    }

    you can use this code as mentioned below:

            self.lblMid.attributedText = AttributedTextwithImgaeSuffixAndPrefix(AttributeImage1: #imageLiteral(resourceName: "Left") , AttributedText: "  Payment Details  ", AttributeImage2: #imageLiteral(resourceName: "RIght") , LabelBound: self.lblMid)

    here you can add images you can replace it with your own:

    Left Image

    Right Image

    Out put will be like this

提交回复
热议问题