我想调整 UIImageView 的大小以恰好适合 UITextView 中一行结束处的下方和一行开始处的正上方。
场景: 我正在使用 NSURLConnection 从 URL 下载图像。然后,我使用 ImageIO 框架调整图像大小以适应屏幕。最后,我将排除路径添加到 UITextView.textContainer,以便文本环绕图像。
问题: 我事先不知道图像的大小,所以我必须调整它的大小以适合。一切都很好,除了图片有时会重叠一条线。
问题: 我如何确保调整图像大小,使其恰好位于一行结束位置的下方和一行开始位置的正上方?
示例:
如您在上面的示例中所见,图片下方的文本不再位于行上。我想我可以从 UIImageView 的高度和 lineHeight 中得到剩余部分,但是我不确定如何处理它。
示例 (int)imageView.bounds.size.height % (int)self.textView.font.lineHeight
非常感谢任何指导!
附言如果我的问题不清楚,请告诉我,我会尝试进一步解释。
最佳答案
感谢@CarstenWitzke,我让它开始工作。我将 NSArribulatedString 与 NSTextAttachment 一起使用。然后,我将图像高度的剩余部分除以 textView.font.lineHeight,并从 textView.font.lineHeight 中减去该高度,然后将差值添加到图像的高度。唯一的问题是调整图像大小以适应新的边界。
例如
UIImage * scaledImage = [UIImage imageWithCGImage:imageRef scale:2 orientation:UIImageOrientationUp];
NSTextAttachment * textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = scaledImage;
int remainder = (int)scaledImage.size.height % (int)floor(self.textView.font.lineHeight);
CGFloat difference = (self.textView.font.lineHeight - remainder);
textAttachment.bounds = CGRectMake(0, 0, scaledImage.size.width, scaledImage.size.height + difference);
NSMutableAttributedString * attributedStringWithImage = [[NSAttributedString attributedStringWithAttachment:textAttachment] mutableCopy];
NSAttributedString * newLineAttributedString = [[NSAttributedString alloc] initWithString:@"\n"];
[self.textView.textStorage appendAttributedString:newLineAttributedString];
[self.textView.textStorage appendAttributedString:attributedStringWithImage];
[self.textView.textStorage appendAttributedString:newLineAttributedString];
编辑:
事实证明,我可以使用 CoreGraphics 框架来填充图像,这样就无需调整图像大小以适应新的边界。
例如
- (UIImage *)image:(UIImage *)image padding:(CGSize)padding
{
CGSize size = CGSizeMake(image.size.width + padding.width, image.size.height + padding.height);
UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
CGContextRef context = UIGraphicsGetCurrentContext();
UIGraphicsPushContext(context);
CGFloat x = (image.size.width + padding.width) - image.size.width;
CGFloat y = (image.size.height + padding.height) - image.size.height;
CGPoint origin = CGPointMake(x, y);
[image drawAtPoint:origin];
UIGraphicsPopContext();
UIImage * paddedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return paddedImage;
}
关于ios - 调整 UIImageView 的大小以恰好在 UITextView 中一行结束的下方和一行开始的上方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27181629/