Files
peko-ios/YuMi/Modules/YMRoom/View/MessageContainerView/View/XPNetImageYYLabel.m
2024-03-25 23:18:36 +08:00

60 lines
2.4 KiB
Objective-C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// NetImageYYLabel.m
// YUMI
//
// Created by zu on 2021/11/2.
//
#import "XPNetImageYYLabel.h"
#import "NetImageView.h"
#import "XPRoomMessageConstant.h"
#import "NSArray+Safe.h"
@implementation XPNetImageYYLabel
- (void)setAttributedText:(NSAttributedString *)attributedText {
NSMutableAttributedString* attributedTextCopy = [attributedText mutableCopy];
CGSize maxSize = CGSizeMake(kRoomMessageMaxWidth - 24, MAXFLOAT);
YYTextLayout * layout = [YYTextLayout layoutWithContainerSize:maxSize text:attributedText];
for (int i = 0; i< layout.attachments.count; i++) {
YYTextAttachment * attachment = [layout.attachments safeObjectAtIndex1:i];
if (!attachment || ![attachment.content isKindOfClass:[NetImageView class]]) continue;
NetImageView* imageView = attachment.content;
NSValue * value = [layout.attachmentRanges safeObjectAtIndex1:i];
NSRange range = value.rangeValue;
if (!imageView.imageUrl) continue;
if (imageView.state == NetImageStateLoaded) {
attributedTextCopy = [self updateNetImageAttribute:imageView attributes:attributedTextCopy range:range];
continue;
}else {
[imageView loadImage:^(UIImage * _Nonnull image, NSURL * _Nonnull url) {
imageView.image = image;
[super setAttributedText:[self updateNetImageAttribute:imageView attributes:attributedTextCopy range:range]];
}];
}
}
[super setAttributedText:attributedTextCopy];
}
- (NSMutableAttributedString*)updateNetImageAttribute:(NetImageView*)imageView attributes:(NSMutableAttributedString*)attributes range:(NSRange)range{
UIImage* image = imageView.image;
CGSize size;
if (image != nil){
CGFloat scale = image.size.width / image.size.height;
// 目前是根据原高度imageView.bounds.size.height等比例缩放图片。
size = CGSizeMake(imageView.bounds.size.height * scale, imageView.bounds.size.height);
imageView.bounds = CGRectMake(0, 0, size.width, size.height);
}else{
size = CGSizeMake(16, 16);
imageView.bounds = CGRectMake(0, 0, 16, 16);
}
NSMutableAttributedString * replaceAttr = [NSMutableAttributedString yy_attachmentStringWithContent:imageView contentMode:UIViewContentModeScaleAspectFit attachmentSize:size alignToFont:[UIFont systemFontOfSize:15.0] alignment:YYTextVerticalAlignmentCenter];
[attributes replaceCharactersInRange:range withAttributedString:replaceAttr];
return attributes;
}
@end