我该如何使用Core Graphics来生成噪声纹理背景?我在噪声部分卡住了,因为在Core Graphics中没有添加噪声滤镜的方法...
我该如何使用Core Graphics来生成噪声纹理背景?我在噪声部分卡住了,因为在Core Graphics中没有添加噪声滤镜的方法...
大约一年后,我找到了答案:
CGImageRef CGGenerateNoiseImage(CGSize size, CGFloat factor) CF_RETURNS_RETAINED {
NSUInteger bits = fabs(size.width) * fabs(size.height);
char *rgba = (char *)malloc(bits);
srand(124);
for(int i = 0; i < bits; ++i)
rgba[i] = (rand() % 256) * factor;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
CGContextRef bitmapContext = CGBitmapContextCreate(rgba, fabs(size.width), fabs(size.height),
8, fabs(size.width), colorSpace, kCGImageAlphaNone);
CGImageRef image = CGBitmapContextCreateImage(bitmapContext);
CFRelease(bitmapContext);
CGColorSpaceRelease(colorSpace);
free(rgba);
return image;
}
// draw background
CGContextFillRect(context, ...)
// blend noise on top
CGContextSetBlendMode(context, kCGBlendModeOverlay);
CGImageRef cgImage = [UIImage imageNamed:@"noise"].CGImage;
CGContextDrawImage(context, rect, cgImage);
CGContextSetBlendMode(context, kCGBlendModeNormal);
iOS 6中的CoreImageFilters有一个CIRandomGenerator。但请注意,这不是高斯噪声(与先前的答案不同)。
- (UIImage*)linearRandomImage:(CGRect)rect
{
CIContext *randomContext = [CIContext contextWithOptions:nil];
CIFilter *randomGenerator = [CIFilter filterWithName: @"CIColorMonochrome"];
[randomGenerator setValue:[[CIFilter filterWithName:@"CIRandomGenerator"] valueForKey:@"outputImage"] forKey:@"inputImage"];
[randomGenerator setDefaults];
CIImage *resultImage = [randomGenerator outputImage];
CGImageRef ref = [randomContext createCGImage:resultImage fromRect:rect];
UIImage *endImage=[UIImage imageWithCGImage:ref];
return endImage;
}
CF_RETURNS_RETAINED
修复。 - Aditya Vaidyam