首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 圖片局部模糊處理:裁剪區域 -> 模糊 -> 合成回原圖的完整方案

     編輯:程式設計綜合問答

需對 UIImageView 中指定區域(圓形/矩形)進行模糊,核心思路:裁剪目標區域 -> 應用模糊濾鏡 -> 合成回原圖對應位置。觸摸移動時實時更新。

核心步驟與關鍵方法

  1. 裁剪區域圖片:
    - (UIImage *)cropImage:(UIImage *)image toRect:(CGRect)rect {
        CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
        UIImage *cropped = [UIImage imageWithCGImage:imageRef];
        CGImageRelease(imageRef);
        return cropped;
    }
    
  2. 高斯模糊(Category 擴展):
    // UIImage+ImageBlur.m
    - (UIImage *)imageWithGaussianBlur9 {
        float weight[5] = {0.127, 0.195, 0.122, 0.054, 0.016};
        UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
        [self drawInRect:CGRectMake(0,0,self.size.width,self.size.height) blendMode:kCGBlendModeNormal alpha:weight[0]];
        for (int x=1; x<5; x++) {
            [self drawInRect:CGRectMake(x,0,self.size.width,self.size.height) blendMode:kCGBlendModeNormal alpha:weight[x]];
            [self drawInRect:CGRectMake(-x,0,self.size.width,self.size.height) blendMode:kCGBlendModeNormal alpha:weight[x]];
        }
        UIImage *hBlur = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        // 垂直同理...
        return vBlur;
    }
    
  3. 圓角處理(可選):
    - (UIImage *)roundedRectImage:(UIImage *)image radius:(CGFloat)r { ... }
    
  4. 合成回原圖:
    - (UIImage *)mergeImage:(UIImage *)base withImage:(UIImage *)overlay atRect:(CGRect)rect {
        UIGraphicsBeginImageContextWithOptions(base.size, NO, base.scale);
        [base drawAtPoint:CGPointZero];
        [overlay drawInRect:rect];
        UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return result;
    }
    
  5. 觸摸移動實時更新:
    - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch *touch = [touches anyObject];
        CGPoint pt = [touch locationInView:imageView];
        // 轉換座標到圖片空間,計算裁剪矩形
        CGRect cropRect = ...;
        UIImage *cropped = [self cropImage:imageView.image toRect:cropRect];
        UIImage *blurred = [cropped imageWithGaussianBlur9];
        UIImage *rounded = [self roundedRectImage:blurred radius:4];
        imageView.image = [self mergeImage:imageView.image withImage:rounded atRect:cropRect];
    }
    

性能提示

  • 模糊運算較重,建議降低處理圖片尺寸或使用 CIFilter (Core Image) 硬件加速。
  • 實時拖拽時可節流(如 30ms 一幀)避免卡頓。

組合繪圖上下文操作,實現精準局部模糊效果。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved