Created
March 22, 2015 22:23
-
-
Save phatmann/582bed5aa0f06432873b to your computer and use it in GitHub Desktop.
NSTextAttachment that scales and aligns image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Created by Tony Mann on 3/22/15. | |
// Copyright (c) 2015 7Actions. All rights reserved. | |
// | |
// Adapted from http://ossh.com.au/design-and-technology/software-development/implementing-rich-text-with-images-on-os-x-and-ios/ | |
import UIKit | |
class ImageAttachment: NSTextAttachment { | |
var verticalOffset: CGFloat = 0.0 | |
// To vertically center the image, pass in the font descender as the vertical offset. | |
// We cannot get this info from the text container since it is sometimes nil when `attachmentBoundsForTextContainer` | |
// is called. | |
convenience init(_ image: UIImage, verticalOffset: CGFloat = 0.0) { | |
self.init() | |
self.image = image | |
self.verticalOffset = verticalOffset | |
} | |
override func attachmentBoundsForTextContainer(textContainer: NSTextContainer, proposedLineFragment lineFrag: CGRect, glyphPosition position: CGPoint, characterIndex charIndex: Int) -> CGRect { | |
let height = lineFrag.size.height | |
var scale: CGFloat = 1.0; | |
let imageSize = image!.size | |
if (height < imageSize.height) { | |
scale = height / imageSize.height | |
} | |
return CGRect(x: 0, y: verticalOffset, width: imageSize.width * scale, height: imageSize.height * scale) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you're working on an objc project: