ios - 快速模糊 UITableViewCell contentView 背景

标签 ios objective-c image performance gpuimage

我制作了一个 UIViewController,它符合 UITableViewDataSourceUITableViewDelegate 协议(protocol),并且有一个 UITableView subview 。

我已将表格的 backgroundView 属性设置为 UIImageView,以便将图像显示为表格的背景。

为了自定义单元格之间的间距,我将行高设置得比我想要的大,并将单元格的 contentView 自定义为我想要的大小,使其看起来像是有额外的空间 ( Following this SO answer )。

我想为单元格添加模糊,使背景模糊,我通过 Brad Larson's GPUImage framework 做到了这一点.然而,这工作正常,因为我希望背景模糊在滚动时更新,滚动变得非常滞后。

我的代码是:

//Gets called from the -scrollViewDidScroll:(UIScrollView *)scrollView method
- (void)updateViewBG
{
    UIImage *superviewImage = [self snapshotOfSuperview:self.tableView];

    UIImage* newBG = [self applyTint:self.tintColour image:[filter imageByFilteringImage:superviewImage]];

    self.layer.contents = (id)newBG.CGImage;
    self.layer.contentsScale = newBG.scale;
}

//Code to create an image from the area behind the 'blurred cell'
- (UIImage *)snapshotOfSuperview:(UIView *)superview
{
    CGFloat scale = 0.5;
    if (([UIScreen mainScreen].scale > 1 || self.contentMode == UIViewContentModeScaleAspectFill)) {
        CGFloat blockSize = 12.0f/5;
        scale = blockSize/MAX(blockSize * 2, floor(self.blurRadius));
    }

    UIGraphicsBeginImageContextWithOptions(self.bounds.size, YES, scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, -self.frame.origin.x, -self.frame.origin.y);
    NSArray *hiddenViews = [self prepareSuperviewForSnapshot:superview];
    [superview.layer renderInContext:context];
    [self restoreSuperviewAfterSnapshot:hiddenViews];
    UIImage *snapshot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshot;
}

-(UIImage*)applyTint:(UIColor*)colour image:(UIImage*)inImage{
    UIImage *newImage;
    if (colour) {
        UIGraphicsBeginImageContext(inImage.size);

        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGRect area = CGRectMake(0, 0, inImage.size.width, inImage.size.height);

        CGContextScaleCTM(ctx, 1, -1);
        CGContextTranslateCTM(ctx, 0, -area.size.height);
        CGContextSaveGState(ctx);
        CGContextClipToMask(ctx, area, inImage.CGImage);
        [[colour colorWithAlphaComponent:0.8] set];
        CGContextFillRect(ctx, area);
        CGContextRestoreGState(ctx);
        CGContextSetBlendMode(ctx, kCGBlendModeLighten);
        CGContextDrawImage(ctx, area, inImage.CGImage);
        newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    } else {
        newImage = inImage;
    }
    return newImage;
}

现在开始提问:
有没有更好的方法来添加模糊?也许这样就不必在每次移动时都渲染图层? iOS7的控制中心/通知中心似乎可以做到这一点,没有任何滞后。

也许使用 GPUImageUIElement 类?如果是这样,我该如何使用它? 我查看的另一种方法是最初在背景图像上创建模糊,然后只裁剪我需要使用的区域,但是我无法让它工作,因为图像可能与或可能不相同屏幕,因此缩放是一个问题(使用 CGImageCreateWithImageInRect() 并且矩形是单元格在表格中的位置)。

我还发现我必须将模糊添加到表格 View 本身,框架是单元格的框架,并且单元格具有清晰的颜色。

提前致谢

编辑 根据要求,这是我之前尝试过的图像裁剪代码:

- (void)updateViewBG
{
    //self.bgImg is the pre-blurred image, -getContentViewFromCellFrame: is a convenience method to get just the content area from the whole cell (since the contentarea is smaller than the cell)
    UIImage* bg = [self cropImage:self.bgImg 
                           toRect:[LATableBlur getContentViewFromCellFrame:[self.tableView rectForRowAtIndexPath:self.cellIndexPath]]];
    bg = [self applyTint:self.tintColour image:bg];
    self.layer.contents = (id)bg.CGImage;
    self.layer.contentsScale = bg.scale;
}

- (UIImage*)cropImage:(UIImage*)image toRect:(CGRect)frame
{
    CGSize imgSize = [image size];
    double heightRatio = imgSize.height/self.tableView.frame.size.height;
    double widthRatio = imgSize.width/self.tableView.frame.size.width;

    UIImage* cropped = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(image.CGImage,
                                                                              CGRectMake(frame.origin.x*widthRatio,
                                                                                         frame.origin.y*heightRatio,
                                                                                         frame.size.width*widthRatio,
                                                                                         frame.size.height*heightRatio))];

    return cropped;
}

最佳答案

我设法用一开始我认为行不通的解决方案解决了这个问题。

生成多个模糊图像肯定不是解决方案,因为它的成本很高。 我只使用了一张模糊图像并将其缓存。

所以我将 UITableViewCell 子类化:

@interface BlurredCell : UITableViewCell
@end

我实现了两个类方法来访问缓存图像(模糊图像和普通图像)

+(UIImage *)normalImage
{
    static dispatch_once_t onceToken;
    static UIImage *_normalImage;
    dispatch_once(&onceToken, ^{
        _normalImage = [UIImage imageNamed:@"bg.png"];
    });
    return _normalImage;
}

我用了REFrostedViewController用于生成模糊图像的 UIImage 类别

+(UIImage *)blurredImage
{
    static dispatch_once_t onceToken;
    static UIImage *_blurredImage;
    dispatch_once(&onceToken, ^{
    _blurredImage = [[UIImage imageNamed:@"bg.png"] re_applyBlurWithRadius:BlurredCellBlurRadius
                                                                 tintColor:[UIColorcolorWithWhite:1.0f
                                                                                            alpha:0.4f]
                                                     saturationDeltaFactor:1.8f
                                                                 maskImage:nil];
    });
    return _blurredImage;
}

为了在单元格内产生模糊帧的效果,但仍能看到侧面的非模糊图像,我曾经 ScrollView 。

一个是正常图像的 ImageView ,另一个是模糊图像的 ImageView 。我将内容大小设置为图像的大小,contentOffset 将通过界面设置。

所以表格 View 最终每个单元格都包含整个背景图像,但以一定的偏移量裁剪它并仍然显示整个图像

@implementation BlurredCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        [self.contentView addSubview:self.normalScrollView];
        [self.contentView addSubview:self.blurredScrollView];
    }
    return self;
}

-(UIScrollView *)normalScrollView
{
    if (!_normalScrollView) {
        _normalScrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        _normalScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _normalScrollView.scrollEnabled = NO;
        UIImageView *imageView =[[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        imageView.contentMode = UIViewContentModeScaleToFill;
        imageView.image = [BlurredCell normalImage];
        _normalScrollView.contentSize = imageView.frame.size;
        [_normalScrollView addSubview:imageView];
    }
    return _normalScrollView;
}

-(UIScrollView *)blurredScrollView
{
    if (!_blurredScrollView) {
        _blurredScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(BlurredCellPadding, BlurredCellPadding,
                                                                            self.bounds.size.width - 2.0f * BlurredCellPadding,
                                                                            self.bounds.size.height - 2.0f * BlurredCellPadding)];
        _blurredScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _blurredScrollView.scrollEnabled = NO;
        _blurredScrollView.contentOffset = CGPointMake(BlurredCellPadding, BlurredCellPadding);
        UIImageView *imageView =[[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        imageView.contentMode = UIViewContentModeScaleToFill;
        imageView.image = [BlurredCell blurredImage];
        _blurredScrollView.contentSize = imageView.frame.size;
        [_blurredScrollView addSubview:imageView];
    }
    return _blurredScrollView;
}

-(void)setBlurredContentOffset:(CGFloat)offset
{
    self.normalScrollView.contentOffset = CGPointMake(self.normalScrollView.contentOffset.x, offset);
    self.blurredScrollView.contentOffset = CGPointMake(self.blurredScrollView.contentOffset.x, offset + BlurredCellPadding);
}

@end

setBlurredContentOffset: 每次 TableView 的内容偏移量更改时都应调用。

所以在 TableView 委托(delegate)的实现( View Controller )中,我们用这两种方法来实现:

// For the first rows
-(void)tableView:(UITableView *)tableView willDisplayCell:(BlurredCell *)cell 
                                        forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [cell setBlurredContentOffset:cell.frame.origin.y];
}

// Each time the table view is scrolled
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    for (BlurredCell *cell in [self.tableView visibleCells]) {
        [cell setBlurredContentOffset:cell.frame.origin.y - scrollView.contentOffset.y];
    }
}

这是一个complete working demo

关于ios - 快速模糊 UITableViewCell contentView 背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19366834/

相关文章:

ios - 下载完成后如何将通过 SDWebImage 下载的图像加载到 View Controller 中?

c# - 降低单点触控中 native <-> 托管交互的成本

ios - 覆盖属性的 setter/getter 时出错

ios - 只有从 [UIColor colorNamed :] even though traitCollection. userInterfaceStyle = Dark 返回的浅色外观颜色

image - 将图像原始大小保留在较小的 div 中

html - 内联图像和 h (HTML/CSS)

javascript - Node.js 服务器不显示图像

objective-c - 比较两个nsstrings的值

c++ - Objective-C++的缺点?

ios - map 上特定位置的用户当前位置