二维码/条形码是按照某种特定的几何图形按一定规律在平台(一维/二维方向上)分布的黑白相间的图形纪录符号信息。使用若干个与二进制对应的几何形体来表示文字数值信息。

最常见的二维码功能包括信息获取、网站跳转、电商交易、手机支付等等,其拥有密度小、信息容量大、容错能力强、成本低、制作难度低等优点。在移动开发中,二维码的地位也越来越重要,掌握二维码的基本操作是重要的本领之一。
在ios7之后,苹果自身集成了二维码的生成和读取功能。生成二维码包括以下步骤
- 导入coreimage/coreimage.h头文件
- 使用cifilter滤镜类生成二维码
- 对生成的二维码进行加工,使其更清晰
除了上述三个步骤之外,我们还可以对二维码进行进一步的拓展处理
- 自定义二维码图案颜色
- 在二维码中心插入圆角小图片
- 在圆角图片下面加上一层圆角白色图片
二维码生成
码农们生产代码的同时永远不要忘记尽可能的复用,那么为了实现这种目的,本文的代码通过类别拓展uiimage的方法来完成。我们先声明并实现一个类方法用来接收二维码存储数据以及二维码尺寸的方法:
?| 1 2 3 4 5 6 7 8 9 |
+ (uiimage *)imageofqrfromurl: (nsstring *)networkaddress codesize: (cgfloat)codesize {
if (!networkaddress|| (nsnull *)networkaddress == [nsnull null]) {
return nil;
}
codesize = [self validatecodesize: codesize];
ciimage * originimage = [self createqrfromaddress: networkaddress];
uiimage * result = [uiimage imagewithciimage: originimage];
return result;
}
|
在上面的代码里面,我们总共做了四件事情:验证存储信息的有效性;验证二维码尺寸的合理大小;使用存储信息生成二维码;将二维码转成uiimage返回。这些方法的实现分别如下:
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
/*! 验证二维码尺寸合法性*/
+ (cgfloat)validatecodesize: (cgfloat)codesize
{
codesize = max(160, codesize);
codesize = min(cgrectgetwidth([uiscreen mainscreen].bounds) - 80, codesize);
return codesize;
}
/*! 利用系统滤镜生成二维码图*/
+ (ciimage *)createqrfromaddress: (nsstring *)networkaddress
{
nsdata * stringdata = [networkaddress datausingencoding: nsutf8stringencoding];
cifilter * qrfilter = [cifilter filterwithname: @"ciqrcodegenerator"];
[qrfilter setvalue: stringdata forkey: @"inputmessage"];
[qrfilter setvalue: @"h" forkey: @"inputcorrectionlevel"];
return qrfilter.outputimage;
}
/! 验证二维码尺寸合法性/
- (cgfloat)validatecodesize: (cgfloat)codesize
{
codesize = max(160, codesize);
codesize = min(cgrectgetwidth([uiscreen mainscreen].bounds) - 80, codesize);
return codesize;
}
/! 利用系统滤镜生成二维码图/
- (ciimage *)createqrfromaddress: (nsstring *)networkaddress
{
nsdata * stringdata = [networkaddress datausingencoding: nsutf8stringencoding];
cifilter * qrfilter = [cifilter filterwithname: @"ciqrcodegenerator"];
[qrfilter setvalue: stringdata forkey: @"inputmessage"];
[qrfilter setvalue: @"h" forkey: @"inputcorrectionlevel"];
return qrfilter.outputimage;
}
|
ps:对于cifilter想要更进一步了解,可以在xcode中使用快捷键shift+command+0打开文档,然后搜索core image filter reference获取更多滤镜的使用方法,这些滤镜可以用来实现类似美图秀秀的修图功能。
上面的代码生成了一个粗略的二维码图,我们需要对图片再进行一次处理,使其清晰化。因为,我们需要另外一个类别方法:
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
/! 对图像进行清晰化处理/
- (uiimage *)excludefuzzyimagefromciimage: (ciimage *)image size: (cgfloat)size
{
cgrect extent = cgrectintegral(image.extent);
cgfloat scale = min(size / cgrectgetwidth(extent), size / cgrectgetheight(extent));
size_t width = cgrectgetwidth(extent) * scale;
size_t height = cgrectgetheight(extent) * scale;
//创建灰度色调空间
cgcolorspaceref colorspace = cgcolorspacecreatedevicegray();
cgcontextref bitmapref = cgbitmapcontextcreate(nil, width, height, 8, 0, colorspace, (cgbitmapinfo)kcgimagealphanone);
cicontext * context = [cicontext contextwithoptions: nil];
cgimageref bitmapimage = [context createcgimage: image fromrect: extent];
cgcontextsetinterpolationquality(bitmapref, kcginterpolationnone);
cgcontextscalectm(bitmapref, scale, scale);
cgcontextdrawimage(bitmapref, extent, bitmapimage);
cgimageref scaledimage = cgbitmapcontextcreateimage(bitmapref);
cgcontextrelease(bitmapref);
cgimagerelease(bitmapimage);
cgcolorspacerelease(colorspace);
return [uiimage imagewithcgimage: scaledimage];
}
|
那么这时候,我们把+(uiimage *)imageofqrfromurl: codesize:的最后改成
uiimage * result =[self excludefuzzyimagefromciimage: originimage size: codesize];
示例完成后生成的二维码效果图如下:

二维码拓展
单一的黑白色二维码并不一定总能满足开发的需求或者说领导的需求。好比现在的应用很多功能界面上都在朝着微信学习,这就包括了更多色彩,更多样式的二维码。本文将从颜色、二维码中心小图案这两点入手讲解如何制作类似微信生成我的二维码的样式。
自定义二维码颜色的实现思路是,遍历生成的二维码的像素点,将其中为白色的像素点填充为透明色,非白色则填充为我们自定义的颜色。但是,这里的白色并不单单指纯白色,rgb值高于一定数值的灰色我们也可以视作白色处理。在这里我对白色的定义为rgb值高于0xd0d0d0的颜色值为白色,这个值并不是确定的,大家可以自己设置。基于颜色的设置,我们将原有生成二维码的方法接口改成这样:
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 |
+ (uiimage *)imageofqrfromurl: (nsstring *)networkaddress codesize: (cgfloat)codesize red: (nsuinteger)red green: (nsuinteger)green blue: (nsuinteger)blue
{
if (!networkaddress || (nsnull *)networkaddress == [nsnull null]) { return nil; }
/** 颜色不可以太接近白色*/
nsuinteger rgb = (red << 16) + (green << 8) + blue;
nsassert((rgb & 0xffffff00) <= 0xd0d0d000, @"the color of qr code is two close to white color than it will diffculty to scan");
codesize = [self validatecodesize: codesize];
ciimage * originimage = [self createqrfromaddress: networkaddress];
uiimage * progressimage = [self excludefuzzyimagefromciimage: originimage size: codesize]; //到了这里二维码已经可以进行扫描了
uiimage * effectiveimage = [self imagefillblackcolorandtransparent: progressimage red: red green: green blue: blue]; //进行颜色渲染后的二维码
return effectiveimage;
}
|
相较于前面的代码,多了两个步骤:判断rgb的有效值;对二维码进行颜色渲染。颜色渲染的过程包括获取图像的位图上下文、像素替换、二进制图像转换等操作,具体代码如下:
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
/*! 对生成二维码图像进行颜色填充*/
+ (uiimage *)imagefillblackcolorandtransparent: (uiimage *)image red: (nsuinteger)red green: (nsuinteger)green blue: (nsuinteger)blue {
const int imagewidth = image.size.width;
const int imageheight = image.size.height;
size_t bytesperrow = imagewidth * 4;
uint32_t * rgbimagebuf = (uint32_t *)malloc(bytesperrow * imageheight);
cgcolorspaceref colorspace = cgcolorspacecreatedevicergb();
cgcontextref context = cgbitmapcontextcreate(rgbimagebuf, imagewidth, imageheight, 8, bytesperrow, colorspace, kcgbitmapbyteorder32little | kcgimagealphanoneskiplast);
cgcontextdrawimage(context, (cgrect){(cgpointzero), (image.size)}, image.cgimage);
//遍历像素
int pixelnumber = imageheight * imagewidth;
[self fillwhitetotransparentonpixel: rgbimagebuf pixelnum: pixelnumber red: red green: green blue: blue];
cgdataproviderref dataprovider = cgdataprovidercreatewithdata(null, rgbimagebuf, bytesperrow, providerreleasedata);
cgimageref imageref = cgimagecreate(imagewidth, imageheight, 8, 32, bytesperrow, colorspace, kcgimagealphalast | kcgbitmapbyteorder32little, dataprovider, null, true, kcgrenderingintentdefault);
uiimage * resultimage = [uiimage imagewithcgimage: imageref];
cgimagerelease(imageref);
cgcolorspacerelease(colorspace);
cgcontextrelease(context);
return resultimage;
}
/! 遍历所有像素点进行颜色替换/
+ (void)fillwhitetotransparentonpixel: (uint32_t *)rgbimagebuf pixelnum: (int)pixelnum red: (nsuinteger)red green: (nsuinteger)green blue: (nsuinteger)blue {
uint32_t * pcurptr = rgbimagebuf;
for (int i = 0; i < pixelnum; i++, pcurptr++) {
if ((*pcurptr & 0xffffff00) < 0xd0d0d000) {
uint8_t * ptr = (uint8_t *)pcurptr;
ptr[3] = red;
ptr[2] = green;
ptr[1] = blue;
} else {
//将白色变成透明色
uint8_t * ptr = (uint8_t *)pcurptr;
ptr[0] = 0;
}
}
}
void providerreleasedata(void * info, const void * data, size_t size) {
free((void *)data);
}
|
ps:在修改代码之前,应该想清楚是否需要删除原有代码。类似这种二维码的扩展,旧的二维码生成接口可以留下来,然后在其中调用多参数的全能构造器designated initializer。

这时候距离微信还差一小步,我们要在二维码的中心位置插入我们的小头像,最直接的方式是加载完我们的头像后,直接drawinrect:这种实现方法是正确的,但是在我们画上去之前,我们还需要对图像进行圆角处理。(省事的可能直接用imageview加载头像,然后设置头像的cornerradius,这个也能实现效果)。
到了这个时候,我们需要一个更多参数的二维码生成方法接口了,这次新增的参数应该包括插入图片、圆角半径这些参数,因此方法如下:
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 |
+ (uiimage *)imageofqrfromurl: (nsstring *)networkaddress codesize: (cgfloat)codesize red: (nsuinteger)red green: (nsuinteger)green blue: (nsuinteger)blue insertimage: (uiimage *)insertimage roundradius: (cgfloat)roundradius {
if (!networkaddress || (nsnull *)networkaddress == [nsnull null]) { return nil; }
/** 颜色不可以太接近白色*/
nsuinteger rgb = (red << 16) + (green << 8) + blue;
nsassert((rgb & 0xffffff00) <= 0xd0d0d000, @"the color of qr code is two close to white color than it will diffculty to scan");
codesize = [self validatecodesize: codesize];
ciimage * originimage = [self createqrfromaddress: networkaddress];
uiimage * progressimage = [self excludefuzzyimagefromciimage: originimage size: codesize]; //到了这里二维码已经可以进行扫描了
uiimage * effectiveimage = [self imagefillblackcolorandtransparent: progressimage red: red green: green blue: blue]; //进行颜色渲染后的二维码
return [self imageinsertedimage: effectiveimage insertimage: insertimage radius: roundradius];
}
|
这次的生成方法同样也只需要进行一次额外的调用方法操作,在插入图片的时候我们需要注意,类似微信的图中图二维码中间的小头像是有一个圆角的白色边缘的,这个边缘的加入让头像显示的更加自然。那么要完成这个效果,我额外在项目中加入了一张白色背景的小图,同样对这张图片进行圆角化处理,然后加在头像的下面。作为头像下方的白色背景图像尺寸应该大于头像图。制作画中画效果的具体实现如下:
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
/! 在二维码原图中心位置插入圆角图像/
+ (uiimage *)imageinsertedimage: (uiimage *)originimage insertimage: (uiimage *)insertimage radius: (cgfloat)radius
{
if (!insertimage) { return originimage; }
insertimage = [uiimage imageofroundrectwithimage: insertimage size: insertimage.size radius: radius];
uiimage * whitebg = [uiimage imagenamed: @"whitebg"];
whitebg = [uiimage imageofroundrectwithimage: whitebg size: whitebg.size radius: radius];
//白色边缘宽度
const cgfloat whitesize = 2.f;
cgsize brinksize = cgsizemake(originimage.size.width / 4, originimage.size.height / 4);
cgfloat brinkx = (originimage.size.width - brinksize.width) * 0.5;
cgfloat brinky = (originimage.size.height - brinksize.height) * 0.5;
cgsize imagesize = cgsizemake(brinksize.width - 2 * whitesize, brinksize.height - 2 * whitesize);
cgfloat imagex = brinkx + whitesize;
cgfloat imagey = brinky + whitesize;
uigraphicsbeginimagecontext(originimage.size);
[originimage drawinrect: (cgrect){ 0, 0, (originimage.size) }];
[whitebg drawinrect: (cgrect){ brinkx, brinky, (brinksize) }];
[insertimage drawinrect: (cgrect){ imagex, imagey, (imagesize) }];
uiimage * resultimage = uigraphicsgetimagefromcurrentimagecontext();
uigraphicsendimagecontext();
return resultimage;
}
- (uiimage *)imageofroundrectwithimage: (uiimage *)image size: (cgsize)size radius: (cgfloat)radius
{
if (!image) { return nil; }
const cgfloat width = size.width;
const cgfloat height = size.height;
radius = max(5.f, radius);
radius = min(10.f, radius);
uiimage * img = image;
cgcolorspaceref colorspace = cgcolorspacecreatedevicergb();
cgcontextref context = cgbitmapcontextcreate(null, width, height, 8, 4 * width, colorspace, kcgimagealphapremultipliedfirst);
cgrect rect = cgrectmake(0, 0, width, height);
//绘制圆角
cgcontextbeginpath(context);
addroundrecttopath(context, rect, radius, img.cgimage);
cgimageref imagemasked = cgbitmapcontextcreateimage(context);
img = [uiimage imagewithcgimage: imagemasked];
cgcontextrelease(context);
cgcolorspacerelease(colorspace);
cgimagerelease(imagemasked);
return img;
}
|
ps:图像绘制圆角是通过在图像上下文中画出圆角矩形的路径,然后进行裁剪,这样就能实现图片的圆角化。

在代码中,对中心位置的头像限制尺寸为二维码的四分之一,这个尺寸下的头像不失清晰度,而且图片尺寸也不至于遮盖了二维码的存储数据。上面的方法都可以在头文件中开发方法接口使用,这将实现这些代码的复用。另外,所有本文中写到的生成二维码的接口都应该在头文件中声明,并且在其实现中调用全能方法(不应当仅仅是构造器需要遵循designated initializer的原则):
?| 1 2 3 4 |
+ (uiimage *)imageofqrfromurl: (nsstring *)networkaddress
{
return [self imageofqrfromurl: networkaddress codesize: 100.0f red: 0 green: 0 blue: 0 insertimage: nil roundradius: 0.f];
}
|
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持服务器之家!
原文链接:http://sindrilin.com/ios-dev/2015/10/26/定制多样式二维码








发表评论
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。