Skip to content

Instantly share code, notes, and snippets.

@yarshure
Forked from snej/QRCode.m
Created December 12, 2016 09:26
Show Gist options
  • Save yarshure/6f8360546aac8cf36456397c61dd5fbd to your computer and use it in GitHub Desktop.
Save yarshure/6f8360546aac8cf36456397c61dd5fbd to your computer and use it in GitHub Desktop.
Shows how to generate a QRCode on iOS or Mac OS X
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
typedef UIImage QRImage;
#else
#import <AppKit/AppKit.h>
typedef NSImage QRImage;
#endif
+ (QRImage*) QRCodeImageWithData: (NSData*)data size: (CGFloat)size {
CIFilter* filter = [CIFilter filterWithName: @"CIQRCodeGenerator"];
[filter setValue: data forKey: @"inputMessage"];
CIImage* ciImage = filter.outputImage;
if (!ciImage)
return nil;
#if TARGET_OS_IPHONE
UIImage* tinyImage = [[UIImage alloc] initWithCIImage: ciImage];
if (size <= tinyImage.size.width)
return tinyImage;
// Scale image up:
UIGraphicsBeginImageContext(CGSizeMake(size, size));
CGContextSetInterpolationQuality(UIGraphicsGetCurrentContext(), kCGInterpolationNone);
[tinyImage drawInRect: CGRectMake(0, 0, size, size)];
UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
#else
NSCIImageRep *rep = [NSCIImageRep imageRepWithCIImage: ciImage];
NSImage* tinyImage = [[NSImage alloc] init];
[tinyImage addRepresentation: rep];
if (size <= rep.size.width)
return tinyImage;
// Scale image up:
NSImage* nsImage = [[NSImage alloc] initWithSize: NSMakeSize(size, size)];
[nsImage lockFocus];
[NSGraphicsContext currentContext].imageInterpolation = NSImageInterpolationNone;
[tinyImage drawInRect: NSMakeRect(0, 0, size, size)];
[nsImage unlockFocus];
return nsImage;
#endif
}
+ (CBImage*) QRCodeImageWithData: (NSData*)data {
return [self QRCodeImageWithData: data size: 500];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment