Skip to content

Instantly share code, notes, and snippets.

@benguild
Last active February 8, 2019 04:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benguild/af3a9d320724bf1f17c96c288c9018e2 to your computer and use it in GitHub Desktop.
Save benguild/af3a9d320724bf1f17c96c288c9018e2 to your computer and use it in GitHub Desktop.
Properly scaled QR Code generator class method for `UIImage` (lightweight, avoids anti-aliasing/blurring)
//
// UIImage+QRCode.h
//
// Created by Ben Guild on 2017/09/17.
// Copyright © 2017年 Ben Guild. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIImage (QRCode)
+ (UIImage *)qrCodeWithString:(NSString *)string
size:(CGSize)size
qrCodeErrorCorrectionLevel:(CIQRCodeErrorCorrectionLevel)qrCodeErrorCorrectionLevel;
@end
//
// UIImage+QRCode.m
//
// Created by Ben Guild on 2017/09/17.
// Copyright © 2017年 Ben Guild. All rights reserved.
//
#import "UIImage+QRCode.h"
@implementation UIImage (QRCode)
+ (UIImage *)qrCodeWithString:(NSString *)string
size:(CGSize)size
qrCodeErrorCorrectionLevel:(CIQRCodeErrorCorrectionLevel)qrCodeErrorCorrectionLevel {
NSString *qrCodeErrorCorrectionLevelAsString;
switch (qrCodeErrorCorrectionLevel) {
case CIQRCodeErrorCorrectionLevelL:
qrCodeErrorCorrectionLevelAsString = @"L";
break;
case CIQRCodeErrorCorrectionLevelM:
qrCodeErrorCorrectionLevelAsString = @"M";
break;
case CIQRCodeErrorCorrectionLevelQ:
qrCodeErrorCorrectionLevelAsString = @"Q";
break;
case CIQRCodeErrorCorrectionLevelH:
qrCodeErrorCorrectionLevelAsString = @"H";
break;
default:
break;
}
CIFilter *qrCodeFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
[qrCodeFilter setDefaults];
[qrCodeFilter setValue:[string dataUsingEncoding:NSISOLatin1StringEncoding
allowLossyConversion:YES] forKey:@"inputMessage"];
if (qrCodeErrorCorrectionLevelAsString != nil) {
[qrCodeFilter setValue:qrCodeErrorCorrectionLevelAsString forKey:@"inputCorrectionLevel"];
}
CIImage *filterOutputImage = [qrCodeFilter valueForKey:kCIOutputImageKey];
UIGraphicsBeginImageContextWithOptions(size, false, 0);
CGContextRef graphicsContext = UIGraphicsGetCurrentContext();
CGContextSetInterpolationQuality(graphicsContext, kCGInterpolationNone);
CGImageRef filterOutputCGImageRef =
[[CIContext contextWithOptions:@{ kCIContextUseSoftwareRenderer: @(YES) }] createCGImage:filterOutputImage
fromRect:filterOutputImage.extent];
CGContextDrawImage(graphicsContext, CGContextGetClipBoundingBox(graphicsContext), filterOutputCGImageRef);
CGImageRelease(filterOutputCGImageRef);
UIImage *qrCode = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return qrCode;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment