How would I ever use Core graphics only to generate a noise texture background? I'm stuck on the noise part because there is no way to add a noise filter in core graphics...
About a year later, I've found the answer:
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;
}
This effectively generates a noise image that's guaranteed to be random, and can be drawn, using the code from Jason Harwig's answer.
Create a noise png, then draw it using an overlay blend.
// draw background
CGContextFillRect(context, ...)
// blend noise on top
CGContextSetBlendMode(context, kCGBlendModeOverlay);
CGImageRef cgImage = [UIImage imageNamed:@"noise"].CGImage;
CGContextDrawImage(context, rect, cgImage);
CGContextSetBlendMode(context, kCGBlendModeNormal);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With