如何解决iOS 13中的此问题?
我正在截取UITextView内容大小的屏幕截图。在iOS 12之前,一切都正常。但是从iOS 13开始出现问题,它没有完整地截取屏幕截图。下面是小于iOS 12和iOS 13及以后的输出图片。
小于iOS 12
以下是我用于截取UITextView屏幕截图的代码:
let textView = UITextView()
UIGraphicsBeginImageContextWithOptions(textView.contentSize, textView.isOpaque, 0.0)
let savedContentOffset: CGPoint = textView.contentOffset
let savedFrame: CGRect = textView.frame
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:- 以下代码使用UILabel
let SCREEN_WIDTH = UIScreen.main.bounds.size.width
let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
func buttonAction() {
let textView = UITextView()
textView.frame = CGRect(x: 10, y: 50, width: SCREEN_WIDTH - 20, height: SCREEN_HEIGHT * 2)
let lab = UILabel(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH - 20, height: textView.contentSize.height))
lab.backgroundColor = UIColor.white
lab.font = textView.font
lab.textColor = UIColor.black
lab.numberOfLines = 0
lab.text = textView.text
textView.addSubview(lab)
UIGraphicsBeginImageContextWithOptions(CGSize(width: SCREEN_WIDTH - 20, height: textView.contentSize.height), _: true, _: 1)
if let context = UIGraphicsGetCurrentContext() {
lab.layer.render(in: context)
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
textView.frame = CGRect(x: 10, y: 50, width: SCREEN_WIDTH - 20, height: SCREEN_HEIGHT * 2)
lab.removeFromSuperview()
}
选项2:- 以下代码使用TempView
let SCREEN_WIDTH = UIScreen.main.bounds.size.width
let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
func buttonAction() {
let textView = UITextView()
textView.frame = CGRect(x: 10, y: 50, width: SCREEN_WIDTH - 20, height: SCREEN_HEIGHT * 2)
UIGraphicsBeginImageContextWithOptions(CGSize(width: SCREEN_WIDTH - 20, height: textView.contentSize.height), _: true, _: 1)
if #available(iOS 13, *) {
// iOS 13 (or newer)
let tempView = UIView(frame: CGRect(x: 0, y: 0, width: textView.contentSize.width, height: textView.contentSize.height))
tempView.addSubview(textView)
if let context = UIGraphicsGetCurrentContext() {
tempView.layer.render(in: context)
}
tempView.removeFromSuperview()
view.addSubview(textView)
} else {
// iOS 12 or older
if let context = UIGraphicsGetCurrentContext() {
textView.layer.render(in: context)
}
}
选项3:
尝试使用第三方库,我使用过YYTextView。https://github.com/ibireme/YYText
UIGraphicsImageRenderer
吗?在 Swift iOS 中截屏? - Cœur