iOS开发

UIImageView超大图显示

2016-11-22  本文已影响300人  囧书

缘起

UIImageView在加载大分辨率图像时,可能无法渲染出来,特别是在模拟器上运行的时候。
可对大图进行切分成一块一块小图,分成多个ImageView加载,然后拼在一起。

实现

JXLargeImageView.h

/// 切分大图,用多个小图来显示。只支持竖直的长图
@interface JXLargeImageView : UIImageView

/// 单块图片最大高度因子,宽度的倍数。默认为5
@property (nonatomic, assign) NSInteger maxHeightFator;

@end

JXLargeImageView.m

- (void)setImage:(UIImage *)image {
    _image = image;
    
    [self.imageViewArray enumerateObjectsUsingBlock:^(UIImageView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    [self.imageViewArray removeAllObjects];
    if (!image) {
        return;
    }
    
    CGFloat imageWidth = image.size.width;
    CGFloat maxImageHeight = imageWidth * self.maxHeightFator;
    if (maxImageHeight == 0) {
        return;
    }
    NSInteger count = ceil(image.size.height / maxImageHeight);
    
    for (NSInteger index = 0; index < count; ++ index) {
        CGFloat height = (index == count - 1) ? image.size.height - maxImageHeight * index : maxImageHeight;
        CGImageRef imgRef = CGImageCreateWithImageInRect(image.CGImage, CGRectMake(0, index * maxImageHeight, imageWidth, height));
        UIImageView *view = [[UIImageView alloc] initWithImage:[UIImage imageWithCGImage:imgRef]];
        view.contentMode = self.contentMode;
        [self addSubview:view];
        [self.imageViewArray addObject:view];
    }
    [self setNeedsLayout];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGFloat imageWidth = self.bounds.size.width;
    CGFloat maxImageHeight = imageWidth * self.maxHeightFator;
    if (maxImageHeight == 0) {
        return;
    }
    NSInteger count = ceil(self.bounds.size.height / maxImageHeight);
    
    [self.imageViewArray enumerateObjectsUsingBlock:^(UIImageView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        CGFloat height = (idx == count - 1) ? self.bounds.size.height - maxImageHeight * idx : maxImageHeight;
        obj.frame = CGRectMake(0, idx * maxImageHeight, imageWidth, height);
    }];
}
JXLargeImageViewJXLargeImageView

源码

https://github.com/JiongXing/JXLargeImageView

上一篇下一篇

猜你喜欢

热点阅读