【发布时间】:2013-08-18 07:11:51
【问题描述】:
我有一个带有UIImageView 和UIImage 设置的视图。如何使用 coregraphics 使图像清晰或模糊?
【问题讨论】:
标签: iphone objective-c cocoa-touch core-graphics
我有一个带有UIImageView 和UIImage 设置的视图。如何使用 coregraphics 使图像清晰或模糊?
【问题讨论】:
标签: iphone objective-c cocoa-touch core-graphics
Apple 有一个很棒的示例程序,名为 GLImageProcessing,其中包含使用 OpenGL ES 1.1 的非常快速的模糊/锐化效果(这意味着它适用于所有 iPhone,而不仅仅是 3gs。)
如果您对 OpenGL 不太熟悉,代码可能会让您头疼。
【讨论】:
对于我的需求来说,沿着 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;
}
【讨论】:
您真正需要的是 CoreImage API 中的图像过滤器。不幸的是,iPhone 不支持 CoreImage(除非最近发生了变化,我错过了它)。这里要小心,因为 IIRC,它们在 SIM 中可用 - 但在设备上不可用。
AFAIK 没有其他方法可以正确使用本机库,尽管我之前通过在顶部创建一个额外的图层来伪造模糊,这是下面内容的副本,偏移一两个像素并且具有较低的 alpha 值。但是,为了获得适当的模糊效果,我能够做到这一点的唯一方法是在 Photoshop 或类似工具中离线。
也很想知道是否有更好的方法,但据我所知,目前的情况就是这样。
【讨论】: