Resizing image before sharing to Instagram Stories?

时间:2019-01-26 20:49:49

标签: ios swift uiimage instagram

The extension below works to resize an image, however whenever I share to IG Stories using the code below the image isn't resized, any idea how I can reduce the size so that it formats nicely?

func shareBackgroundImage() {
    let image = UIImage(imageLiteralResourceName: "backgroundImage").resize(newWidth: CGFloat(150))

    if let pngImage = image.pngData() {
        backgroundImage(pngImage, attributionURL: "http://your-deep-link-url")
    }
}

func backgroundImage(_ backgroundImage: Data, attributionURL: String) {
    // Verify app can open custom URL scheme, open if able

    guard let urlScheme = URL(string: "instagram-stories://share"),
        UIApplication.shared.canOpenURL(urlScheme) else {
            // Handle older app versions or app not installed case

            return
    }

    let pasteboardItems = [["com.instagram.sharedSticker.backgroundImage": backgroundImage,
                            "com.instagram.sharedSticker.contentURL": attributionURL]]
    let pasteboardOptions: [UIPasteboard.OptionsKey: Any] = [.expirationDate: Date().addingTimeInterval(60 * 5)]

    // This call is iOS 10+, can use 'setItems' depending on what versions you support
    UIPasteboard.general.setItems(pasteboardItems, options: pasteboardOptions)

    UIApplication.shared.open(urlScheme)
}

extension UIImage {

    func resize(withWidth newWidth: CGFloat) -> UIImage? {

        let scale = newWidth / self.size.width
        let newHeight = self.size.height * scale
        UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
        self.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage
    }
}

0 个答案:

没有答案