Skip to content

Instantly share code, notes, and snippets.

@kgn
Created June 28, 2012 18:11
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kgn/3012995 to your computer and use it in GitHub Desktop.
Save kgn/3012995 to your computer and use it in GitHub Desktop.
Noise in Cocoa
+ (void)drawNoiseWithOpacity:(CGFloat)opacity inRect:(CGRect)rect{
static UIImage *noiseImage = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
NSUInteger width = 64, height = 64;
NSUInteger size = width*height;
char *rgba = (char *)malloc(size); srand(124);
for(NSUInteger i=0; i < size; ++i){rgba[i] = rand()%256;}
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
CGContextRef bitmapContext =
CGBitmapContextCreate(rgba, width, height, 8, width, colorSpace, kCGImageAlphaNone);
CFRelease(colorSpace);
CGImageRef noiseImageRef = CGBitmapContextCreateImage(bitmapContext);
CFRelease(bitmapContext);
free(rgba);
if([[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2){
noiseImage = [UIImage imageWithCGImage:noiseImageRef scale:2 orientation:UIImageOrientationUp];
}else{
noiseImage = [UIImage imageWithCGImage:noiseImageRef];
}
CGImageRelease(noiseImageRef);
});
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextSetAlpha(context, opacity);
CGContextSetBlendMode(context, kCGBlendModeScreen);
[noiseImage drawAsPatternInRect:rect];
CGContextRestoreGState(context);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment