写本文的初衷:因为公司最近在研发自己的仓库管理系统,作为一个iOS屌丝,本来就不关事;但老大看我闲的蛋疼,就叫我去生成并打印一百多个仓库条形码,刚开始时候用网页的条形码生成工具生成,妈蛋!一百多个啊。。。一个一个生成,保存,你不知道对于程序员来说会死的!!所以打算用iOS写一个脚本,输入完条形码内容,一次性生成几十个条形码图片!
于是乎,开始了哥的网上大开搜。。。。。。。。。。。。。。。。
结论就是源码太少,解释更少啦!而且还没有条形码底部的文字说明!所以,就自己动手写咯!!!
实现:
一、生成条形码
直接上码啦:
func generateBarCode128(barCodeStr:String,barCodeSize:CGSize) ->UIImage? {
//将传入的string转成nsstring,再编码
let stringData = barCodeStr.dataUsingEncoding(NSUTF8StringEncoding)
//系统自带能生成的码
// CIAztecCodeGenerator 二维码
// CICode128BarcodeGenerator 条形码
// CIPDF417BarcodeGenerator
// CIQRCodeGenerator 二维码
let qrFilter = CIFilter(name: "CICode128BarcodeGenerator")
qrFilter?.setDefaults()
qrFilter?.setValue(stringData, forKey: "inputMessage")
let outputImage:CIImage? = qrFilter?.outputImage
/*
生成的条形码需要对其进行消除模糊处理,本文提供两种方法消除模糊,其原理都是放大条码,但项目中需要在条码底部加上条码内容文字,使用其方法一会模糊并变小文字,所以使用方法二,需要各位去研究下原因哈。。。
*/
// 消除模糊方法一
// let context = CIContext()
// let cgImage = context.createCGImage(outputImage!, fromRect: outputImage!.extent)
// let image = UIImage(CGImage: cgImage, scale: 1.0, orientation: UIImageOrientation.Up)
//
// // Resize without interpolating
// let scaleRate:CGFloat = 20.0
// let resized = resizeImage(addText(image), quality: CGInterpolationQuality.None, rate: scaleRate)
// 消除模糊方法二
let scaleX:CGFloat = barCodeSize.width/outputImage!.extent.size.width; // extent 返回图片的frame
let scaleY:CGFloat = barCodeSize.height/outputImage!.extent.size.height;
let resultImage = outputImage?.imageByApplyingTransform(CGAffineTransformScale(CGAffineTransformIdentity, scaleX, scaleY))
let image = UIImage.init(CIImage: resultImage!)
return addText(image,textName: barCodeStr);
}
二、对生成的条形码加上文字
//添加条形码下方文字
func addText(image:UIImage,textName:String) ->UIImage{
let size = CGSizeMake(image.size.width, image.size.height+30)
UIGraphicsBeginImageContextWithOptions (size, false , 0.0 );
image.drawAtPoint(CGPointZero)
// 获得一个位图图形上下文
let context = UIGraphicsGetCurrentContext ();
CGContextDrawPath (context!, .Stroke );
//绘制文字
let barText:NSString = textName
let textStyle = NSMutableParagraphStyle()
textStyle.lineBreakMode = .ByWordWrapping
textStyle.alignment = .Center
barText.drawInRect(CGRectMake(0, image.size.height-4, size.width, 30), withAttributes: [NSFontAttributeName:UIFont.systemFontOfSize(18.0),NSBackgroundColorAttributeName:UIColor.clearColor(),NSParagraphStyleAttributeName:textStyle])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
三、最后一步:将加工过的条形码存入本地
//写入本地
func writeToLocal(image:UIImage,imgName:String) {
let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray).objectAtIndex(0)
let filePath = "\(path)/\(imgName).jpeg"
// let fileurl = __stringToUrl(filePath)
let imgData = UIImageJPEGRepresentation(image, 0)
if imgData != nil {
imgData!.writeToFile(filePath, atomically: true)
print("写入成功!!")
print("filePath=\(filePath)")
}
}
好了,方法都写好了,所以现在就用我们的代码生成几十张条形码吧!因为是将生成的条形码存入本地,所以跑这个应用需要用模拟器来跑,这样你就能用command+shift+G快捷键打开打印出来的文件路径啦!激动不?~~~
调用:
override func viewDidLoad() {
super.viewDidLoad()
barCodeNameArray = ["SN00000000001","SN00000000002","SN00000000003","SN00000000005","SN00000000006","SN00000000007","SN00000000008","SN00000000009","SN000000000010","SN00000000011","SN00000000012","SN00000000013","SN00000000014","SN00000000015","SN00000000015","SN00000000016","SN00000000017","SN00000000018","SN00000000019"]
for codeName in barCodeNameArray {
//异步生成条形码,并保存到本地
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
dispatch_async(queue) {
//生成条形码
let image = self.generateBarCode128(codeName,barCodeSize: self.barCodeSize)
if image != nil {
self.writeToLocal(image!,imgName: codeName)
}
}
}
}