iPhone:模糊UIImage [英] iPhone: Blur UIImage

查看:133
本文介绍了iPhone:模糊UIImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的iPhone应用程序中,我有一个黑白 UIImage 。我需要模糊该图像(高斯模糊会这样做)。

In my iPhone application I have a black-and-white UIImage. I need to blur that image (Gaussian blur would do).

iPhone显然知道如何模糊图像,如它会在绘制阴影时执行此操作

iPhone clearly knows how to blur images, as it does that when it draws shadows.

但是我没有在API中找到任何相关内容。

However I did not found anything related in the API.

我是否必须手动模糊,没有硬件加速?

Do I have to do blurring by hand, without hardware acceleration?

推荐答案

试试这个(找到这里):

@interface UIImage (ImageBlur)
- (UIImage *)imageWithGaussianBlur;
@end

@implementation UIImage (ImageBlur)
- (UIImage *)imageWithGaussianBlur {
    float weight[5] = {0.2270270270, 0.1945945946, 0.1216216216, 0.0540540541, 0.0162162162};
    // Blur horizontally
    UIGraphicsBeginImageContext(self.size);
    [self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height) blendMode:kCGBlendModePlusLighter alpha:weight[0]];
    for (int x = 1; x < 5; ++x) {
        [self drawInRect:CGRectMake(x, 0, self.size.width, self.size.height) blendMode:kCGBlendModePlusLighter alpha:weight[x]];
        [self drawInRect:CGRectMake(-x, 0, self.size.width, self.size.height) blendMode:kCGBlendModePlusLighter alpha:weight[x]];
    }
    UIImage *horizBlurredImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    // Blur vertically
    UIGraphicsBeginImageContext(self.size);
    [horizBlurredImage drawInRect:CGRectMake(0, 0, self.size.width, self.size.height) blendMode:kCGBlendModePlusLighter alpha:weight[0]];
    for (int y = 1; y < 5; ++y) {
        [horizBlurredImage drawInRect:CGRectMake(0, y, self.size.width, self.size.height) blendMode:kCGBlendModePlusLighter alpha:weight[y]];
        [horizBlurredImage drawInRect:CGRectMake(0, -y, self.size.width, self.size.height) blendMode:kCGBlendModePlusLighter alpha:weight[y]];
    }
    UIImage *blurredImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    //
    return blurredImage;
}

并按如下方式使用:

UIImage *blurredImage = [originalImage imageWithGaussianBlur];

要获得更强的模糊,只需将此效果应用两次或更多次:)

To get stronger blur just apply this effect twice or more :)

这篇关于iPhone:模糊UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆