我有一个带有UIImageView
的视图,上面设置了一个UIImage
。如何使用CoreGraphics使图像变得清晰或模糊?
我有一个带有UIImageView
的视图,上面设置了一个UIImage
。如何使用CoreGraphics使图像变得清晰或模糊?
对于我的需求(在图像上模糊触摸点),走OpenGL路线感觉过于繁琐。因此,我实现了一个简单的模糊处理过程,它会获取触摸点,创建包含该触摸点的矩形,对该点进行采样,然后将采样的图像倒置并多次绘制在源矩形上,每次都略微偏移和透明度不同。这样可以产生一个相当不错的低成本模糊效果,而且代码量和复杂度也不会太高。代码如下:
- (UIImage*)imageWithBlurAroundPoint:(CGPoint)point {
CGRect bnds = CGRectZero;
UIImage* copy = nil;
CGContextRef ctxt = nil;
CGImageRef imag = self.CGImage;
CGRect rect = CGRectZero;
CGAffineTransform tran = CGAffineTransformIdentity;
int indx = 0;
rect.size.width = CGImageGetWidth(imag);
rect.size.height = CGImageGetHeight(imag);
bnds = rect;
UIGraphicsBeginImageContext(bnds.size);
ctxt = UIGraphicsGetCurrentContext();
// Cut out a sample out the image
CGRect fillRect = CGRectMake(point.x - 10, point.y - 10, 20, 20);
CGImageRef sampleImageRef = CGImageCreateWithImageInRect(self.CGImage, fillRect);
// Flip the image right side up & draw
CGContextSaveGState(ctxt);
CGContextScaleCTM(ctxt, 1.0, -1.0);
CGContextTranslateCTM(ctxt, 0.0, -rect.size.height);
CGContextConcatCTM(ctxt, tran);
CGContextDrawImage(UIGraphicsGetCurrentContext(), rect, imag);
// Restore the context so that the coordinate system is restored
CGContextRestoreGState(ctxt);
// Cut out a sample image and redraw it over the source rect
// several times, shifting the opacity and the positioning slightly
// to produce a blurred effect
for (indx = 0; indx < 5; indx++) {
CGRect myRect = CGRectOffset(fillRect, 0.5 * indx, 0.5 * indx);
CGContextSetAlpha(ctxt, 0.2 * indx);
CGContextScaleCTM(ctxt, 1.0, -1.0);
CGContextDrawImage(ctxt, myRect, sampleImageRef);
}
copy = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return copy;
}
苹果公司有一个非常好的示例程序叫做GLImageProcessing,其中包括使用OpenGL ES 1.1实现的非常快速的模糊/锐化效果(这意味着它适用于所有iPhone,而不仅仅是3gs)。
如果您对OpenGL的经验不够丰富,那么这些代码可能会让您感到头痛。
你真正需要的是CoreImage API中的图像过滤器。不幸的是,除非最近有所改变而我没有注意到,否则iPhone不支持CoreImage。要小心,在SIM卡上它们是可用的,但在设备上不可用。
据我所知,没有其他方法可以使用本地库来正确地完成它,尽管我曾经通过在顶部创建一个额外的图层来模拟模糊效果,该图层是下面内容的副本,偏移了一个或两个像素,并具有较低的alpha值。对于适当的模糊效果,我唯一能够做到的就是在Photoshop或类似软件中离线处理。
如果有更好的方法,我很乐意听听,但据我所知,目前情况就是这样。