效果图:
源码:
// // ViewController.m // CodeCreator // // Created by YouXianMing on 15/3/16. // Copyright (c) 2015年 YouXianMing. All rights reserved. // #import "ViewController.h" @interface ViewController () @property (nonatomic, strong) UIImageView *imageView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)]; self.imageView.center = self.view.center; [self.view addSubview:self.imageView]; [self generateCode]; } - (UIImage *)resizeImage:(UIImage *)image withQuality:(CGInterpolationQuality)quality rate:(CGFloat)rate { UIImage *resized = nil; CGFloat width = image.size.width * rate; CGFloat height = image.size.height * rate; UIGraphicsBeginImageContext(CGSizeMake(width, height)); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetInterpolationQuality(context, quality); [image drawInRect:CGRectMake(0, 0, width, height)]; resized = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return resized; } - (void)generateCode { // @"CICode128BarcodeGenerator" 条形码 // @"CIAztecCodeGenerator" 二维码 NSString *filtername = @"CICode128BarcodeGenerator"; CIFilter *filter = [CIFilter filterWithName:filtername]; [filter setDefaults]; NSData *data = [@"YouXianMing" 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]; // Resize without interpolating CGFloat scaleRate = self.imageView.frame.size.width / image.size.width; UIImage *resized = [self resizeImage:image withQuality:kCGInterpolationNone rate:scaleRate]; self.imageView.image = resized; CGImageRelease(cgImage); } @end
时间: 2024-10-10 08:48:17