Maximilian Krause
Maximilian Krause

Reputation: 1155

Image in NSTextAttachment too big and blurry

I'm trying to place an icon (in form of an image) next to a text in a UILabel. The icons are imported into the assets in al three sizes and are not blurry at all when I simply place them in a normal UIImageView. However, within the NSTextAttachment they suddenly become extremely blurry and are too big, as well.

I already tried several things on my own and also tried nearly every snippet I could find online - nothing helps. This is what I'm left over with:

func updateWinnableCoins(coins: Int){
    let attachImg =  NSTextAttachment()
    attachImg.image = resizeImage(image: #imageLiteral(resourceName: "geld"), targetSize: CGSize(width: 17.0, height: 17.0))
    attachImg.setImageHeight(height: 17.0)
    let imageOffsetY:CGFloat = -3.0;
    attachImg.bounds = CGRect(x: 0, y: imageOffsetY, width: attachImg.image!.size.width, height: attachImg.image!.size.height)
    let attchStr = NSAttributedString(attachment: attachImg)
    let completeText = NSMutableAttributedString(string: "")
    let tempText = NSMutableAttributedString(string: "You can win " + String(coins) + " ")
    completeText.append(tempText)
    completeText.append(attchStr)
    self.lblWinnableCoins.textAlignment = .left;
    self.lblWinnableCoins.attributedText = completeText;
}

func resizeImage(image: UIImage, targetSize: CGSize) -> (UIImage) {

    let newRect = CGRect(x: 0, y: 0, width: targetSize.width, height: targetSize.height).integral
    UIGraphicsBeginImageContextWithOptions(targetSize, false, 0)
    let context = UIGraphicsGetCurrentContext()

    // Set the quality level to use when rescaling
    context!.interpolationQuality = CGInterpolationQuality.default
    let flipVertical = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: targetSize.height)

    context!.concatenate(flipVertical)
    // Draw into the context; this scales the image
    context?.draw(image.cgImage!, in: CGRect(x: 0.0,y: 0.0, width: newRect.width, height: newRect.height))

    let newImageRef = context!.makeImage()! as CGImage
    let newImage = UIImage(cgImage: newImageRef)

    // Get the resized image from the context and a UIImage
    UIGraphicsEndImageContext()

    return newImage
}

extension NSTextAttachment {
    func setImageHeight(height: CGFloat) {
        guard let image = image else { return }
        let ratio = image.size.width / image.size.height

        bounds = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: ratio * height, height: height)
    }
}

And this is how it looks:

enter image description here

The font size of the UILabel is 17, so I set the text attachment to be 17 big, too. When I set it to 9, it fits, but it's still very blurry.

What can I do about that?

Upvotes: 0

Views: 321

Answers (0)

Related Questions