Search code examples
iosswiftimessage-extension

Swift - resize image iMessage app


I am making an iMessage app with images for a keyboard app like custom emojis. I have setup outlets on my iMessage story board and connected the button. In my MessageViewController I have the code below in my IBOulet. I want to resize the image smaller but I can't seem to figure this one out. Any help is greatly appreciated!

@IBAction func button(_ sender: Any) { 
    label.text = "button pressed"
    let layout = MSMessageTemplateLayout()
    layout.image = UIImage(named: "270a.png")
    let message = MSMessage()
    message.layout = layout
    activeConversation?.insert(message, completionHandler: nil) 
}

Solution

  • When you add an image to message template you can request a width and height, but it will scale the image up or down (respecting the aspect ratio) to a size that it thinks is best.

    If the image resource you have isn't the size you want, you can attempt to create a new image in memory, but MSMessageTemplateLayout will modify this as it sees fit.

    let original = UIImage(named: "background")
    
    // use CGContext to create new image in memory
    // 10 x 10 is super small, so messages app will scale this up
    let image = CGSize(width: 10, height: 10).image { context, frame in
    
        original?.draw(in: frame, blendMode: .luminosity, alpha: 1)
    }
    
    let message = MSMessage()
    let layout = MSMessageTemplateLayout()
    
    layout.image = image
    message.layout = layout
    
    self.activeConversation?.insert(message, completionHandler: nil)
    

    I like to use this extension to make it a little easier working with CGContext: https://gist.github.com/mathewsanders/94ed8212587d72684291483905132790