Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gaussian Noise using Core Graphics only?

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...

like image 467
Aditya Vaidyam Avatar asked Feb 10 '11 16:02

Aditya Vaidyam


2 Answers

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.

like image 200
Aditya Vaidyam Avatar answered Dec 20 '22 06:12

Aditya Vaidyam


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);
like image 42
Jason Harwig Avatar answered Dec 20 '22 07:12

Jason Harwig