chrisdhaan / CDMarkdownKit

An extensive Swift framework providing simple and customizable markdown parsing.
MIT License
254 stars 65 forks source link

Image scaling #7

Closed AliceAponasko closed 6 years ago

AliceAponasko commented 6 years ago

What did you do?

Parsed an image link with a large image.

What did you expect to happen?

The image to fit in the textView.

What happened instead?

The image was too large and didn't scale.

CDMarkdownKit Environment

CDMarkdownKit version: 0.9.7
Xcode version: 9.2 (9C40b)
Swift version: 3.2
Platform(s) running CDMarkdownKit: iOS
macOS version running Xcode: MacOS Sierra 10.12.6


Possible solution to this is to pass a desired frame to CDMarkdownParser and initialize CDMarkdownImage with it. Then, scale the attachment size to fit the passed frame.

    private func adjustAttachmentSize(_ attachment: NSTextAttachment, image: UIImage) {
        guard let frame = frame else {
            return
        }

        // about 10 point padding so the image will fit
        let preferredWidth = frame.width - 10
        let widthScalingFactor = image.size.width / preferredWidth

        attachment.bounds = CGRect(x: 0.0,
                                   y: 0.0,
                                   width: image.size.width / widthScalingFactor,
                                   height: image.size.height / widthScalingFactor)
    }

Another possible solution is to parse customElements before defaultElements in CDMarkdownParser. Then developers have an option to create a custom class for scaled images and pass that as a custom element.

chrisdhaan commented 6 years ago

@AliceAponasko thanks for pointing this out. I like both of your proposed solutions. Do you think one is more beneficial than the other?

AliceAponasko commented 6 years ago

@chrisdhaan I think it's better to provide an optional frame, so developers have less work to do. If set, the image will resize to fit in that frame.

I also think it is beneficial to parse custom elements first because some developers might have their own implementations of library's classes.

I submitted a PR, let me know if oyu have any questions!

chrisdhaan commented 6 years ago

@AliceAponasko I've pushed up a commit with this functionality. Would it be alright to close out this issue?

chrisdhaan commented 6 years ago

Haven't heard anything back and this seems to be working now so closing issue.