我有一個UITextView
我添加圖像,與ImagePickerController。UITextView滯後滾動添加圖像
如果其中只有文本,它是平滑的,但添加3或4張圖片後,其內容中的滾動會變得遲緩。
我在添加圖像時會壓縮圖像,因爲圖像的質量最差,但是我必須做一些錯誤的操作,因爲它仍然滯後於第三張圖像。
下面的代碼:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let _image = info[UIImagePickerControllerOriginalImage] as? UIImage else { return }
self.dismiss(animated: true, completion: nil)
// Compress the retrieved image
let compressedImage = UIImage(data: _image.lowestQualityJPEGNSData!)
//create and NSTextAttachment and add your image to it.
let attachment = NSTextAttachment()
let oldWidth = compressedImage?.size.width // scales it within the UITextView
let scaleFactor = oldWidth!/(bodyEditText.frame.size.width - 10); // adjusts the desired padding
attachment.image = UIImage(cgImage: (compressedImage?.cgImage!)!, scale: scaleFactor, orientation: .up)
//put your NSTextAttachment into and attributedString
let attString = NSAttributedString(attachment: attachment)
//add this attributed string to the current position.
bodyEditText.textStorage.insert(attString, at: bodyEditText.selectedRange.location)
}
extension UIImage {
var uncompressedPNGData: Data? { return UIImagePNGRepresentation(self) }
var highestQualityJPEGNSData: Data? { return UIImageJPEGRepresentation(self, 1.0) }
var highQualityJPEGNSData: Data? { return UIImageJPEGRepresentation(self, 0.75) }
var mediumQualityJPEGNSData: Data? { return UIImageJPEGRepresentation(self, 0.5) }
var lowQualityJPEGNSData: Data? { return UIImageJPEGRepresentation(self, 0.25) }
var lowestQualityJPEGNSData:Data? { return UIImageJPEGRepresentation(self, 0.0) }
}
什麼可能會導致此問題的任何提示,我怎麼能立交橋呢?
感謝您的幫助
編輯
感謝鄧肯C I已經設法刪除整個滯後和提高性能的渲染圖像了很多。
通過,我已經取代了我imagePickerController
具有以下內容:
let size = __CGSizeApplyAffineTransform(_image.size, CGAffineTransform.init(scaleX: 0.3, y: 0.3))
let hasAlpha = false
let scale: CGFloat = 0.0 // Automatically use scale factor of main screen
UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
_image.draw(in: CGRect(origin: CGPoint.zero, size: size))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let att = NSTextAttachment()
att.image = scaledImage
//put your NSTextAttachment into and attributedString
let attString = NSAttributedString(attachment: att)
//add this attributed string to the current position.
bodyEditText.textStorage.insert(attString, at: bodyEditText.selectedRange.location)
有一兩件事,我沒有檢索到的圖像設置爲一個ImageView的,我將其添加爲附件的NSAttributedString;我該如何aspectFit呢? –
感謝您的回答我相信我會解決我的問題與您的解釋 –
哦,我沒有看到這一部分。你有代碼'attachment.image = ...'縮放你的圖像後,將其分配給attachment.image。 –