Skip to content

Instantly share code, notes, and snippets.

@mhmtkrgz
Created May 20, 2019 13:54
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 mhmtkrgz/c19f152232d5f0ff651a2f4651d38993 to your computer and use it in GitHub Desktop.
Save mhmtkrgz/c19f152232d5f0ff651a2f4651d38993 to your computer and use it in GitHub Desktop.
QRCode&Barcode
#import <UIKit/UIKit.h>
@interface CodeGenerator : NSObject
+ (UIImage *)qrCodeForString:(NSString *)string;
+ (UIImage *)barCodeForString:(NSString *)string;
@end
#pragma mark - QRCode
+ (UIImage *)qrCodeForString:(NSString *)string {
if (!string.length) return nil;
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
[filter setDefaults];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
[filter setValue:data forKey:@"inputMessage"];
CIImage *outputImage = [filter outputImage];
CIContext *context = [CIContext contextWithOptions:nil];
CGImageRef cgImage = [context createCGImage:outputImage
fromRect:[outputImage extent]];
UIImage *image = [UIImage imageWithCGImage:cgImage
scale:1.
orientation:UIImageOrientationUp];
UIImage *resizedImage = [CodeGenerator resizeImage:image
rate:5.0];
CGImageRelease(cgImage);
return resizedImage;
}
#pragma mark - Barcode
+ (UIImage *)barCodeForString:(NSString *)string {
if (!string.length) return nil;
CIFilter *barCodeFilter = [CIFilter filterWithName:@"CICode128BarcodeGenerator"];
[barCodeFilter setDefaults];
NSData *barCodeData = [string dataUsingEncoding:NSASCIIStringEncoding];
[barCodeFilter setValue:barCodeData forKey:@"inputMessage"];
[barCodeFilter setValue:[NSNumber numberWithFloat:0] forKey:@"inputQuietSpace"];
CIImage *outputImage = [barCodeFilter outputImage];
CIContext *context = [CIContext contextWithOptions:nil];
CGImageRef cgImage = [context createCGImage:outputImage
fromRect:[outputImage extent]];
UIImage *image = [UIImage imageWithCGImage:cgImage
scale:1.
orientation:UIImageOrientationUp];
UIImage *resizedImage = [CodeGenerator resizeImage:image
rate:5.0];
CGImageRelease(cgImage);
return resizedImage;
}
#pragma mark - Util
+ (UIImage *)resizeImage:(UIImage *)image rate:(CGFloat)rate {
UIImage *resized = nil;
CGFloat width = image.size.width * rate;
CGFloat height = image.size.height * rate;
CGInterpolationQuality quality = kCGInterpolationNone;
UIGraphicsBeginImageContext(CGSizeMake(width, height));
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetInterpolationQuality(context, quality);
[image drawInRect:CGRectMake(0, 0, width, height)];
resized = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resized;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment