Gaussian Noise using Core Graphics only?

How would I use Core graphics to only create background texture noise? I am stuck on the noise part because there is no way to add a noise filter to the main graphics ...

+5
source share
3 answers

After about a year, I 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 is guaranteed to be random and can be drawn using the code from Jason Harvig's answer.

+4
source

Create a png noise, then draw it using an overlay.

// draw background
CGContextFillRect(context, ...)

// blend noise on top
CGContextSetBlendMode(context, kCGBlendModeOverlay);
CGImageRef cgImage = [UIImage imageNamed:@"noise"].CGImage;
CGContextDrawImage(context, rect, cgImage);
CGContextSetBlendMode(context, kCGBlendModeNormal);
+3
source

CIRandomGenerator CoreImageFilters iOS 6. , ( ).

- (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;
}
+2

All Articles