我使用UITextView作为富文本视图
- (void)openPhotoLibrary {
[self presentImagePickerController:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (void)presentImagePickerController:(UIImagePickerControllerSourceType)sourceType {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = sourceType;
[self presentViewController:picker animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *dataImage = UIImageJPEGRepresentation(image, 0.1);
UIImage *resultImage = [UIImage imageWithData:dataImage];
[self insertImageOfTheTextView:self.textview withImage:resultImage];
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)insertImageOfTheTextView:(UITextView *)textView withImage:(UIImage *)image {
if (image == nil || ![image isKindOfClass:[UIImage class]]) {
return;
}
NImageAttachment *attachment = [[NImageAttachment alloc] init];
attachment.image = image;
attachment.imageSize = [self scaleImageSize:image];
NSAttributedString *imageAttributedString = [self insertImageDoneAutoReturn:[NSAttributedString attributedStringWithAttachment:attachment]];
[textView.textStorage insertAttributedString:imageAttributedString atIndex:textView.selectedRange.location];
textView.selectedRange = NSMakeRange(textView.selectedRange.location + 3, 0);
}
- (CGSize)scaleImageSize:(UIImage *)image {
CGFloat imageScale = image.size.width / image.size.height;
CGFloat imageWidth = self.view.frame.size.width;
CGSize imageSize = CGSizeMake(imageWidth, imageWidth / imageScale);
return imageSize;
}
- (NSAttributedString *)insertImageDoneAutoReturn:(NSAttributedString *)imageAttributedString {
NSAttributedString *returnAttributedString = [[NSAttributedString alloc] initWithString:@"\n"];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:imageAttributedString];
[attributedString appendAttributedString:returnAttributedString];
[attributedString insertAttributedString:returnAttributedString atIndex:0];
return attributedString;
}
如果我从PhotoLibrary中挑选的照片很小,那么uitextivew就可以了,如果照片很大,当我滚动或编辑uitextview时,uitextview会很慢,看起来很困难,我该如何优化呢?