需對 UIImageView 中指定區域(圓形/矩形)進行模糊,核心思路:裁剪目標區域 -> 應用模糊濾鏡 -> 合成回原圖對應位置。觸摸移動時實時更新。
- (UIImage *)cropImage:(UIImage *)image toRect:(CGRect)rect {
CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return cropped;
}
// 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;
}
- (UIImage *)roundedRectImage:(UIImage *)image radius:(CGFloat)r { ... }
- (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;
}
- (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) 硬件加速。組合繪圖上下文操作,實現精準局部模糊效果。