代码示例
- (void)click
{
UIImage *image = [self imageBarcodeWithContent:@"http://www.hao123.com" size:CGSizeMake(200.0, 100.0)];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[self.view addSubview:imageView];
imageView.backgroundColor = [UIColor colorWithWhite:0.2 alpha:0.1];
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.frame = CGRectMake((self.view.frame.size.width - 200.0f) / 2, 20.0, 200.0f, 200.0f);
}
示例效果
效果图
功能代码
// 条形码尺寸大小
+ (UIImage *)imageBarcodeWithContent:(NSString *)content size:(CGSize)size
{
CIFilter *qrFilter = [CIFilter filterWithName:@"CICode128BarcodeGenerator"];
NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
[qrFilter setValue:contentData forKey:@"inputMessage"];
[qrFilter setValue:@(0.00) forKey:@"inputQuietSpace"];
CIImage *image = qrFilter.outputImage;
CGRect integralRect = CGRectIntegral(image.extent);
CGFloat scale = MIN(size.width / CGRectGetWidth(integralRect), size.height / CGRectGetHeight(integralRect));
size_t width = CGRectGetWidth(integralRect)*scale;
size_t height = CGRectGetHeight(integralRect)*scale;
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceGray();
CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, colorSpaceRef, (CGBitmapInfo)kCGImageAlphaNone);
CIContext *context = [CIContext contextWithOptions:nil];
CGImageRef bitmapImage = [context createCGImage:image fromRect:integralRect];
CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
CGContextScaleCTM(bitmapRef, scale, scale);
CGContextDrawImage(bitmapRef, integralRect, bitmapImage);
CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
CGContextRelease(bitmapRef);
CGImageRelease(bitmapImage);
return [UIImage imageWithCGImage:scaledImage];
}
网友评论