iOS 13 UITextView converting UITextView to image is not working properly. Working fine in below iOS 12

安稳与你 提交于 2019-11-28 02:02:27

问题


How to solve this issue in iOS 13? I am taking screenshot of UITextView content size..Till iOS 12 everything is working fine. But issue with iOS 13 onwards it's not taking full screenshot it's cutting. Below is output picture for less than iOS 12 and after iOS 13. Less than iOS 12

Below is code I'm using to take screenshot of UITextView:

UIGraphicsBeginImageContextWithOptions(textView.contentSize, textView.isOpaque, 0.0)
let savedContentOffset: CGPoint = textView.contentOffset
let savedFrame: CGRect = textView.frame
self.textView.frame = CGRect(x: 0, y: 0, width: textView.contentSize.width, height: textView.contentSize.height)
textView.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
textView.contentOffset = savedContentOffset
textView.frame = savedFrame
UIGraphicsEndImageContext()

回答1:


Don't draw the layer, use the attributedText instead

let size = self.textView.contentSize
UIGraphicsBeginImageContextWithOptions(size, self.textView.isOpaque, 0)
//the textView has 8 margin
textView.attributedText.draw(in: CGRect.init(x: 0, y: 0, width: size.width - 16, height: size.height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()



回答2:


The following worked for me

extension UITextView {
/**
 Convert TextView to UIImage
 */
 func toImage() -> UIImage? {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0.0)
    defer { UIGraphicsEndImageContext() }
    if let context = UIGraphicsGetCurrentContext() {
        self.layer.render(in: context)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        return image
    }
    return nil
  }
}

Use:

UIImageWriteToSavedPhotosAlbum(self.textView.toImage()!,self, nil, nil)



回答3:


Seems that the issue is with the layer for me setting the content size for the layer worked. before the render in context set the layer frame property with the size required this will draw the complete content in the image. hope this helps




回答4:


To get this to work, I had to use a UILabel when rendering.

It's configured with the same constraints/font/text as the textview, and when rendering - set the text in the label, hide the textview and show the label, and vice versa. Perhaps a little less complicated for me since the view I am rendering is not on the screen, but might still be an option.



来源:https://stackoverflow.com/questions/58405106/ios-13-uitextview-converting-uitextview-to-image-is-not-working-properly-workin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!