DSF_QRCode 20.5.0

DSF_QRCode 20.5.0

Darren Ford维护。



 
依赖于
SwiftQRCodeGenerator~> 2.0.2
SwiftImageReadWrite~> 1.9.1
 

DSF_QRCode 20.5.0

  • Darren Ford

QRCode

一个简单的 macOS/iOS/tvOS/watchOS QR Code 生成/检测库,适用于 SwiftUI、Swift 和 Objective-C。

Swift Package Manager

     

为什么?

  • 当您需要显示 QR 码时,有一个简单、快速的内置组件真是太好了!
  • 让你的应用看起来棒极了也是一件好事!

功能

  • 支持 Swift 和 Objective-C。
  • 支持 Swift 包管理器和 CocoaPods
  • 无需 UI 即可生成 QR 码。
  • 支持所有纠错等级。
  • 可配置静区
  • 支持加载/保存
  • 支持 SwiftUI、NSView(macOS)和 UIView(iOS/tvOS)的即时显示集成。
  • 生成图像、可缩放 PDF、可缩放 SVG 和 CGPath 路径。
  • 可配置设计。
  • 将logo添加到 QR 码中。
  • 为图像生成可配置的填充样式(纯色、线性渐变、径向渐变)。
  • 可配置圆角半径
  • 命令行工具,用于从命令行生成 QR 码(macOS 10.13+)。
  • 基本 QR 码视频检测(通过导入 QRCodeDetector)。

安装

Swift 包管理器

要在项目中使用,请将以下依赖项添加到您的 Package.swift

.package(url: "https://github.com/dagronf/qrcode.git", from: "17.0.0")

CocoaPods

要安装它,只需在 Podfile 中添加以下行

pod 'DSF_QRCode', '~> 17.0.0'

使用方法

生成漂亮的二维码的核心功能位于QRCode库中。

如果您想使用二维码视频检测,需要导入QRCodeDetector库。将这两个功能分别放入不同的库中的原因是因为视频检测需要您的应用程序在包含的APP中定义NSCameraUsageDescription(同时添加AVFoundation依赖项),如果您将APP上传到应用商店,这可能不是您想要的——如果您觉得应用不需要这项功能的话!

  • 对于二维码生成,链接到QRCode
  • 对于二维码视频检测,链接到QRCodeDetector

在您的源代码中

Swift: import QRCode

Objective-C: @import QRCode;

使用Tuist或类似工具

QRCode库在核心支持Objective-C,允许在Swift和Objective-C中同时使用。

尽管在Xcode中直接使用QRCode会自动支持这一特性,但确保链接到Objective-C库是很重要的。如果不这样做,您将在运行时遇到崩溃(这并不是理想的情况)。

您需要确保您的链接器标志OTHER_LDFLAGS包含-ObjC

例如,使用Tuist,您需要添加以下内容…

settings: Settings(
   base: [
      "OTHER_LDFLAGS": "-ObjC"
   ],
   ...
)

生成二维码

QRCode.Document类是您将与之交互的核心类。它与任何表现层都不绑定,并在苹果操作系统之间跨平台。

您可以使用此类生成二维码,并将结果呈现为CGPathCGImage。如果您使用Swift,还可以获取原始二维码数据作为2D布尔数组,以便按需使用。

您可以轻松创建基本的黑白二维码图像。

let doc = QRCode.Document(utf8String: "Hi there!", errorCorrection: .high)
let generated = doc.cgImage(CGSize(width: 800, height: 800))

生成

您可以进一步美化二维码(见下文)

简单示例
let doc = QRCode.Document()
doc.utf8String = "This is a test"
doc.errorCorrection = .high

// Set the background color to clear
doc.design.backgroundColor(CGColor.clear)

// Set the foreground color to blue
doc.design.foregroundColor(CGColor.blue)

// Generate a CGPath object containing the QR code
let path = doc.path(CGSize(width: 400, height: 400))

// Generate an image using the default styling (square, black foreground, white background) with 3x resolution
let image = doc.uiImage(CGSize(width: 400, height: 400), dpi: 216)

// Generate pdf data containing the qr code
let pdfdata = doc.pdfData(CGSize(width: 400, height: 400))

// Save a JSON representation of the qrcode document
let jsonData = try doc.jsonData()

// Load a qr code from json
let loadedDoc = try QRCode.Document(jsonData: jsonData)

还有一些扩展到CGImage,以帮助生成二维码变得更加简单

let qrCodeImage = CGImage.qrCode("Hi there!", dimension: 800)

设置

设置数据内容

/// Set raw data
@objc public var data: Data

/// Set a string
public func setString(
   _ string: String, 
   encoding: String.Encoding = .utf8, 
   allowLossyConversion: Bool = false) -> Bool

/// Set raw data using a qrcode message formatter
@objc func setMessage(_ message: QRCodeMessageFormatter)

设置错误纠正

@objc public var errorCorrection: QRCode.ErrorCorrection = .quantize

QRCode.Document具有4种不同的编码级别

错误纠正 描述
最低错误纠正(L - 恢复7%的数据)
中等 中等错误纠正(M - 恢复15%的数据)
量化 量化错误纠正(Q - 恢复25%的数据)
高错误纠正(H - 恢复30%的数据)

错误纠正级别越高,二维码就越大。

设计

QRCode 提供了多种设计 QR 码的方式。默认情况下,QR 码将以传统形式生成 - 正方形,黑色前景和白色背景。通过调整 QR 码的设计设置,您可以使其更加精致。

注意 您可以设计和修饰您的 QR 码,以至于它无法再被读取器读取。

  1. 始终确认您的 QR 码以用户展示的大小可以被读取。(提示:使用您的手机!)
  2. QR 码及其背景之间要有良好的对比度
  3. 如果您使用“关闭像素”(见下文),请确保它们与“开启像素”有极高的对比度。
  4. “开启像素”与眼睛之间没有高对比度。

设计包含两个方面 :-

描述
形状 QR 码中每个单独组件的形状
样式 QR 码中每个单独组件的填充样式

您可以为 QR 码的每个组件分别指定形状和填充样式。

QR 码组件

QRCode 由四个不同的组件组成

  • “开启”数据像素(onPixels
  • 眼睛,由一个 eye(眼睛的外部部分)和一个 pupil(眼睛的内部部分)组成。
  • “关闭”数据像素(offPixels

眼睛形状

您可以为生成的 QR 码的 eyes 提供一个 EyeShape 对象来样式化。内置的生成器包括正方形、圆形、圆角矩形等。

预览 名称 描述
"square" QRCode.EyeShape.Square 简单正方形(默认)
"circle" QRCode.EyeShape.Circle 简单圆形
"圆角矩形" QRCode.EyeShape.RoundedRect 简单圆角矩形
"圆角外型" QRCode.EyeShape.RoundedOuter 外角圆角正方形
"圆角指向内" QRCode.EyeShape.RoundedPointingIn 内角为点的圆角矩形
"树叶形状" QRCode.EyeShape.Leaf 看起来像树叶的眼睛
"超级椭圆形状(在正方形和圆形之间)" QRCode.EyeShape.Squircle 一种超级椭圆形状(介于正方形和圆形之间)
"水平条形" QRCode.EyeShape.BarsHorizontal 带有三个水平条形作为瞳孔的简单圆角矩形
"垂直条形" QRCode.EyeShape.BarsVertical 带有三个垂直条形作为瞳孔的简单圆角矩形
"像素组" QRCode.EyeShape.Pixels 一个简单的像素集合,每个像素都具有可配置的角半径
"带角的像素组" QRCode.EyeShape.CorneredPixels 一个简单的像素集合,整个形状具有可配置的角半径
"边缘" QRCode.EyeShape.Edges 带有可配置角半径的简单边框条形
"盾形" QRCode.EyeShape.Shield 具有可配置角半径的盾形

自定义瞳孔形状(可选)

您可以提供对默认 EyeShape 瞳孔形状的覆盖,以仅更改瞳孔的形状。有内置的生成器用于正方形、圆形、圆角矩形等。

如果您未覆盖瞳孔形状,则默认为眼睛的瞳孔形状。

预览 名称 描述
"square" QRCode.PupilShape.Square 简单正方形(默认)
"circle" QRCode.PupilShape.Circle 简单圆形
"圆角矩形" QRCode.PupilShape.RoundedRect 简单圆角矩形
"圆角外型" QRCode.PupilShape.RoundedOuter 外角圆角正方形
"圆角指向内" QRCode.PupilShape.RoundedPointingIn 具有内角为点的圆角矩形
"圆角指向外" QRCode.PupilShape.RoundedPointingOut 具有外角为点的圆角矩形
"树叶形状" QRCode.PupilShape.Leaf 看起来像树叶的眼睛
"超级椭圆形状(在正方形和圆形之间)" QRCode.PupilShape.Squircle 一种超级椭圆形状(介于正方形和圆形之间)
"水平条形" QRCode.PupilShape.BarsHorizontal 带有三个水平条形作为瞳孔的简单圆角矩形
"垂直条形" QRCode.PupilShape.BarsVertical 带有三个垂直条形作为瞳孔的简单圆角矩形
"像素组" QRCode.PupilShape.Pixel 一个简单的像素集合,每个像素都具有可配置的角半径
"带角的像素组" QRCode.PupilShape.CorneredPixels 一个简单的像素集合,整个形状具有可配置的角半径
"盾形" QRCode.PupilShape.Shield 具有可配置角半径的盾形
示例
let doc = QRCode.Document(utf8String: "Custom pupil")
doc.design.style.background = QRCode.FillStyle.Solid(CGColor.white)
doc.design.shape.eye = QRCode.EyeShape.Squircle()
doc.design.style.eye = QRCode.FillStyle.Solid(0.149, 0.137, 0.208)
doc.design.shape.pupil = QRCode.PupilShape.BarsHorizontal()
doc.design.style.pupil = QRCode.FillStyle.Solid(0.314, 0.235, 0.322)
doc.design.style.onPixels = QRCode.FillStyle.Solid(0.624, 0.424, 0.400)

'OnPixels' 形状

数据形状表示 QR 码内部像素的显示方式。默认情况下,这是一个简单的正方形,但您也可以提供一个 PixelShape 实例来自定义绘制数据。有多种内置样式。

预览 名称 描述
"square" QRCode.PixelShape.Square 基本正方形像素(默认)
"circle" QRCode.PixelShape.Circle 基本圆形像素
"曲线像素" QRCode.PixelShape.CurvePixel 曲线跟随路径的像素
"圆角矩形" QRCode.PixelShape.RoundedRect 基本圆角矩形像素,具有可配置的半径
"水平像素" QRCode.PixelShape.Horizontal 像素水平连接以创建连续的水平条形
"垂直像素" QRCode.PixelShape.Vertical 像素被垂直连接,形成连续的垂直条形
"roundedPath" QRCode.PixelShape.RoundedPath 平滑的圆角路径
"roundedEndIndent" QRCode.PixelShape.RoundedEndIndent 圆角路径,两端有圆形凹口
"超级椭圆形状(在正方形和圆形之间)" QRCode.PixelShape.Squircle 一种超级椭圆形状(介于正方形和圆形之间)
"pointy" QRCode.PixelShape.Pointy ‘尖锐’风格
"sharp" QRCode.PixelShape.Sharp “锋利”样式
"star" QRCode.PixelShape.Star “星形”样式
"flower" QRCode.PixelShape.Flower “花朵”样式
"shiny" QRCode.PixelShape.Shiny 看起来“发光”的像素样式

‘offPixels’ 形状(可选)

您可以为数据像素关闭时绘制的形状指定一个形状。这可以使您的二维码更美观。但是需要记住,您添加到二维码上的装饰越多,越难阅读。

确保‘offPixels’形状和‘onPixels’形状之间有高度的色彩对比,以帮助读者。

QRCode 源
let doc1 = QRCode.Document(utf8String: "Hi there noodle")
doc1.design.backgroundColor(NSColor.white.cgColor)
doc1.design.shape.eye = QRCode.EyeShape.RoundedOuter()
doc1.design.shape.onPixels = QRCode.PixelShape.Circle()
doc1.design.style.onPixels = QRCode.FillStyle.Solid(NSColor.systemGreen.cgColor)
doc1.design.shape.offPixels = QRCode.PixelShape.Horizontal(insetFraction: 0.4, cornerRadiusFraction: 1)
doc1.design.style.offPixels = QRCode.FillStyle.Solid(NSColor.systemGreen.withAlphaComponent(0.4).cgColor)

// Set a custom pupil shape. If this isn't set, the default pixel shape for the eye is used
doc1.design.shape.pupil = QRCode.PupilShape.BarsHorizontal()

// Generate a image for the QRCode
let cgImage = doc1.cgImage(CGSize(width: 300, height: 300))

填充样式

您可以提供二维码各单个组件的自定义填充。

  • ‘onPixels’
  • 眼睛(外部)
  • 瞳孔(内部)
  • ‘offPixels’

QRCode 源
let doc2 = QRCode.Document(utf8String: "Github example for colors")
doc2.design.backgroundColor(NSColor.white.cgColor)
doc2.design.shape.eye = QRCode.EyeShape.RoundedOuter()
doc2.design.shape.onPixels = QRCode.PixelShape.RoundedPath()

// Eye color
doc2.design.style.eye = QRCode.FillStyle.Solid(NSColor.systemGreen.cgColor)
// Pupil color
doc2.design.style.pupil = QRCode.FillStyle.Solid(NSColor.systemBlue.cgColor)
// Data color
doc2.design.style.onPixels = QRCode.FillStyle.Solid(NSColor.systemBrown.cgColor)

// Generate a image for the QRCode
let cgImage = doc2.cgImage(CGSize(width: 300, height: 300))

此库支持当前填充类型。

  • 纯色填充(QRCode.FillStyle.Solid
  • 线性渐变(QRCode.FillStyle.LinearGradient
  • 径向渐变(QRCode.FillStyle.RadialGradient
  • 图像(QRCode.FillStyle.Image

样式示例

有一个红色的径向填充的简单二维码。

QRCode 源
let doc3 = QRCode.Document(utf8String: "Github example for colors")
doc3.design.style.background = QRCode.FillStyle.Solid(CGColor.white)

// Set the fill color for the data to radial gradient
let radial = QRCode.FillStyle.RadialGradient(
   DSFGradient(pins: [
      DSFGradient.Pin(CGColor(red: 0.8, green: 0, blue: 0, alpha: 1), 0),
      DSFGradient.Pin(CGColor(red: 0.1, green: 0, blue: 0, alpha: 1), 1)
   ])!,
   centerPoint: CGPoint(x: 0.5, y: 0.5)
)
doc3.design.style.onPixels = radial

// Generate a image for the QRCode
let cgImage = doc3.cgImage(CGSize(width: 300, height: 300))

将徽标添加到二维码

使用 QRCode.LogoTemplate 类来定义二维码上的徽标。文档中有一个 logoTemplate 成员,可以在其中设置(参见以下示例)

警告

添加徽标会严重影响二维码识别内容的能力。如果您添加了徽标,建议将错误校正级别设置为 .high。覆盖超过25%数据的徽标在读取时往往会导致比成功更多的失败。

在添加图像后,重要的是要验证二维码是否可以被读取(大多数手机摄像头可以读取二维码)。如果徽标最终覆盖了超过25%的数据,那么您的二维码在一些读取器上可能很难被读取。在报告关于二维码无法读取的错误之前,请先移除图像并重试。如果在不添加图像的情况下可以读取代码,则说明您的徽标过大。

方法1:徽标遮罩

最简单的方法是提供一个徽标和可选的透明图像遮罩。如果未提供遮罩,库将使用徽标图像中的透明度信息为您生成遮罩。

图像和遮罩图像应该具有相同的大小并呈正方形,以获得最佳结果。在应用之前,徽标和遮罩都将缩放到最后二维码的大小。

徽标 遮罩 结果
示例图像和遮罩示例

徽标和遮罩

let doc = QRCode.Document(utf8String: "Adding a logo to a QR code using an image and a mask image", errorCorrection: .high)
let logoImage = ... some logo image ...
let logoMaskImage = ... some mask image ...
doc.logoTemplate = QRCode.LogoTemplate(logoImage: logoImage, maskImage: logoMaskImage)
徽标 遮罩 结果

仅徽标

let doc = QRCode.Document(utf8String: "Adding a logo to a QR code using an image's transparency", errorCorrection: .high)
let logoImage = ... some logo image ...
doc.logoTemplate = QRCode.LogoTemplate(logoImage: logoImage)
徽标 结果

方法2:徽标模板

徽标模板定义了图像和二维码中要绘制图像的相对路径。

相对路径代表了二维码“数据”部分中图像绘制的区域。它表示二维码内的一个相对路径(即x=0.0, y=0.0, 宽度=1.0, 高度=1.0)。

x=0.0, y=0.0表示二维码的左上角

例如,如果您想在二维码的中心放置一个圆形徽标,其大小为二维码的1/3,则路径定义如下:-

let path = CGPath(ellipseIn: CGRect(x: 0.35, y: 0.30, width: 0.3, height: 0.3), transform: nil)

(请注意,1/3大小的掩模将很可能会使二维码无法读取:-)

二维码右下角一个1/4大小的矩形徽标将如下所示:-

let path = CGPath(rect: CGRect(x: 0.75, y: 0.75, width: 0.25, height: 0.25), transform: nil)

掩模路径仅影响二维码内的onPixelsoffPixels。徽标落在视觉边界内时将被裁剪。

有多个预构建的LogoTemplate创建器,用于“标准”徽标位置。

  • 圆形中心(QRCode.LogoTemplate.CircleCenter
  • 圆形右下角(QRCode.LogoTemplate.CircleBottomRight
  • 正方形中心(QRCode.LogoTemplate.SquareCenter
  • 正方形右下角(QRCode.LogoTemplate.SquareBottomRight
徽标模板示例

示例 1

// Define a rectangle mask within the bounds of the QR code. A centered square, 30% of the qr code size.
let doc = QRCode.Document(...)

doc.logoTemplate = QRCode.LogoTemplate(
   path: CGPath(rect: CGRect(x: 0.35, y: 0.35, width: 0.30, height: 0.30), transform: nil), 
   inset: 3,
   image: UIImage(named: "square-logo")?.cgImage
)

let qrCodeWithLogo = doc.nsImage(dimension: 300)

生成

示例 2

二维码右下角的一个圆形徽标

let doc = QRCode.Document(...)
doc.logoTemplate = QRCode.LogoTemplate(
   path: CGPath(ellipseIn: CGRect(x: 0.7, y: 0.7, width: 0.30, height: 0.30), transform: nil),
   inset: 8
)
let image = NSImage(named: "instagram-icon")!
let qrCodeWithLogo = doc.uiImage(dimension: 300, image: image)

生成

静区

您可以通过在样式对象上设置 additionalQuietZonePixels 来在二维码外部添加静区,这代表了实际二维码外部添加的像素间距。

请注意,背景颜色/图片/填充不受静区影响(始终延伸到生成的图像边界)

默认情况下,静区设置为 0 像素。

0 像素 5 像素 10 像素 15 像素 背景图片
带 6 像素
let doc = QRCode.Document(utf8String: "https://swiftlang.cn/about/")
doc.design.style.background = QRCode.FillStyle.Solid(0.410, 1.000, 0.375)
doc.design.additionalQuietZonePixels = 4
let qrcodeImage = doc.cgImage(CGSize(width: 300, height: 300))

背景圆角

您可以在样式对象中指定背景填充角的圆角,以分数二维码数据像素值表示。

默认情况下,圆角设置为 0。

0 像素 2 像素 4 像素 6 像素
背景圆角示例
let doc = QRCode.Document(utf8String: "Corner radius checking")
doc.design.style.background = QRCode.FillStyle.Solid(1, 0, 0)
doc.design.foregroundStyle(QRCode.FillStyle.Solid(1, 1, 1))
doc.design.additionalQuietZonePixels = 2
doc.design.style.backgroundFractionalCornerRadius = 3.0
let qrcodeImage = doc.cgImage(CGSize(width: 300, height: 300))

消息格式化器

存在许多与二维码读者兼容的二维码数据格式,例如包含电话号码或联系详情的二维码。

存在一些生成的内置格式化器以生成一些常见的二维码类型。这些可以在 messages 子文件夹中找到。

  • 网址(链接)
  • 生成电子邮件(邮件)
  • 电话号码(电话)
  • 联系详情(联系)
  • UTF-8 格式的字符串(文本)

生成输出

生成路径

@objc func path(_ size: CGSize, components: Components, design: QRCode.Design) -> CGPath

生成二维码的 CGPath 表示形式

  • 生成的路径的像素大小
  • 包含在路径中的二维码组件(默认为标准的二维码组件)
    • 眼睛的“外环”
    • 眼睛的瞳孔
    • 二维码内部的“开启”像素
    • 二维码内部的“关闭”像素
  • 二维码组件的形状

这些组件允许调用者生成二维码组件的单独路径,之后可以单独样式设置并在以后重新组合。

还有在 CGPath 上的扩展,使其能够更容易地从二维码生成 CGPath

let qrcodePath = CGPath.qrCode("This is a test!!!", dimension: 800)

生成一个样式化的图像

@objc func cgImage(_ size: CGSize, dpi: CGFloat = 72.0) -> CGImage?

从二维码生成 CGImage,使用(可选的)设计对象来样式化二维码

@objc func nsImage(_ size: CGSize, dpi: CGFloat = 72.0) -> NSImage?

(仅限 macOS) 使用(可选的)设计对象来样式化二维码生成 NSImage

@objc func uiImage(_ size: CGSize, dpi: CGFloat = 72.0) -> UIImage?

(仅限 iOS/tvOS/watchOS/macCatalyst) 使用(可选的)设计对象来样式化二维码生成 UIImage

生成一个样式化的、可缩放的二维码 PDF 表示形式

@objc func pdfData(_ size: CGSize, pdfResolution: CGFloat) -> Data?

使用(可选的)设计对象和分辨率来样式化和生成二维码的可缩放 PDF

生成二维码的 SVG 表示形式

@objc func svg(dimension: Int) -> String

生成二维码的 SVG 表示形式。

将二维码添加到剪贴板(macOS/iOS)

将多个二维码表示形式添加到指定的剪贴板

平台 新增类型
macOS PDF/PNG/TIFF
iOS PDF/PNG
@objc func addToPasteboard(pasteboard: NSPasteboard = NSPasteboard.general, _ size: CGSize, dpi: CGFloat = 72.0)
@objc func addToPasteboard(pasteboard: UIPasteboard = UIPasteboard.general, _ size: CGSize, dpi: CGFloat = 72.0)

生成二维码文本表示

@objc func asciiRepresentation() -> String

使用扩展ASCII码集返回二维码的ASCII表示

只有在使用固定宽度字体的情况下才有意义。

@objc func smallAsciiRepresentation() -> String

使用扩展ASCII码集返回一个小的ASCII二维码表示(大约是常规尺寸的一半)

只有在使用固定宽度字体的情况下才有意义。

展示

此库提供用于展示样式化二维码的内置组件。

NSView/UIView

QRCodeDocumentView

QRCodeDocumentView 是一个用于显示 QRCode.Document 对象的视图实现。

QRCodeView

QRCodeView 是一个用于显示二维码的视图实现。此视图支持以下功能:

  • 通过 Interface Builder 使用 @IBDesignable,您可以在 Interface Builder 中完全设计并设置二维码的样式,无需拥有 QRCode.Document 对象。
  • (可选)支持将二维码拖拽出视图。

SwiftUI

QRCodeViewUI

将时尚二维码添加到您的 SwiftUI 应用程序的最简单方法。《QRCodeViewUI》是一个 SwiftUI 视图,用于显示具有基本样式的二维码。

QRCodeViewUI(
   content: "This is a test",
   foregroundColor: CGColor(srgbRed: 1, green: 0.8, blue: 0.6, alpha: 1.0),
   backgroundColor: CGColor(srgbRed: 0.2, green: 0.2, blue: 0.8, alpha: 1.0),
   pixelStyle: QRCode.PixelShape.RoundedPath(cornerRadiusFraction: 0.7, hasInnerCorners: true),
   eyeStyle: QRCode.EyeShape.RoundedRect()
)

QRCodeDocumentViewUI

如果您需要更多控制二维码的样式和内容,QRCodeDocumentViewUI 是一个 SwiftUI 视图,用于显示 QRCode.Document 对象。

   var body: some View {
         VStack {
            QRCodeDocumentUIView(document: doc)
         }
         .padding()
   }

QRCodeShape

QRCodeShape 是一个 SwiftUI 形状对象,可以生成来自二维码不同组件的路径。

因此,您可以使用如矩形等任何 SwiftUI 形状对象所能做到的所有事情(例如设置颜色内容(例如线性渐变、纯色等),添加阴影,添加变换等)。

例如,您可以使用 .fill 来设置颜色内容(例如线性渐变、纯色等),添加阴影,添加变换等...

示例
let qrContent = QRCodeShape(myData)
...
ZStack {
   qrContent
      .components(.eyeOuter)
      .fill(.green)
   qrContent
      .components(.eyePupil)
      .fill(.teal)
   qrContent
      .components(.onPixels)
      .fill(.black)
}

修饰符

func errorCorrection(_ errorCorrection: QRCode.ErrorCorrection) -> QRCodeShape {

设置错误校正等级

func components(_ components: QRCode.Components) -> QRCodeShape

设置要添加到路径的QR码组件

func shape(_ shape: QRCode.Shape) -> QRCodeShape

设置形状(onPixels, offPixels, 眼睛,瞳孔)

func eyeShape(_ eyeShape: QRCodeEyeShape) -> QRCodeShape

设置眼睛的形状(眼睛和瞳孔)

func pupilShape(_ pupilShape: QRCodePupilShape) -> QRCodeShape

设置瞳孔的形状

func onPixelShape(_ pixelShape: QRCodePixelShape) -> QRCodeShape

设置QR码中'on'像素的形状

func offPixelShape(_ pixelShape: QRCodePixelShape) -> QRCodeShape

设置QR码中'off'像素的形状

func relativeMaskPath(_ maskPath: CGPath) -> QRCodeShape

设置遮罩路径

示例
struct ContentView: View {

   @State var content: String = "This is a test of the QR code control"
   @State var correction: QRCodeView.ErrorCorrection = .low

   var body: some View {
      Text("Here is my QR code")
      QRCodeShape(
         text: content,
         errorCorrection: correction
      )
      .fill(LinearGradient(gradient: gradient, startPoint: .topLeading, endPoint: .bottomTrailing))
      .shadow(color: .black, radius: 1, x: 1, y: 1)
      .frame(width: 250, height: 250, alignment: .center)
   }
}

Objective-C

QRCode库完全支持Objective-C。

示例
QRCode* code = [[QRCode alloc] init];
[code updateWithText: @"This message"
     errorCorrection: QRCodeErrorCorrectionMax];

QRCodeStyle* style = [[QRCodeStyle alloc] init];

// Set the foreground color to a solid red
style.onPixels = [[QRCodeFillStyleSolid alloc] init: CGColorCreateGenericRGB(1, 0, 0, 1)];

// Use the leaf style
style.shape.eyeShape = [[QRCodeEyeStyleLeaf alloc] init];

// Generate the image
CGImageRef image = [code image: CGSizeMake(400, 400) scale: 1.0 style: style];
NSImage* nsImage = [[NSImage alloc] initWithCGImage:image size: CGSizeZero];

加载/保存

QRCode.Document类提供加载/保存QR码定义到JSON格式的功能。

let qrCode = QRCode.Document()
qrCode.data = "this is a test".data(using: .utf8)!
qrCode.design.shape.onPixels = QRCode.PixelShape.Circle()
qrCode.design.shape.eye = QRCode.EyeShape.Leaf()

let jsonData = try qrCode.jsonData()

...

let loadedQRCode = try QRCode.Document.Create(jsonData: jsonData)

检测QR码

从图像中

库提供了一个机制来检测图像中的QR码。

// CGImage/NSImage/UIImage detection
if let detected = QRCode.DetectQRCodes(in: /*some image*/),
   detected.count > 0 {
   // Do something with the detected qr codes
   let qrCodeBounds = detected[0].bounds
   let qrCodeMessage = detected[0].messageString
   ...
}

更加简单的是,CGImage 拓展可以检测图像中编码的字符串,如果您只想获取每个匹配项的字符串内容。

let image = CGImage(...)
let messages = image.qrCodedMessages()

从视频流中

为了允许在不允许相机使用的情况下在 App Store 或 Test Flight 目标中使用 QRCode,已经将视频检测组件提取为独立的 QRCodeDetector 目标。

有一个视频检测类 QRCodeDetector.VideoDetector,它适用于视频流的基于基本二维码检测。

有两个基本的示例演示了如何在视频流中进行二维码检测。

  • macOS QRCode 检测器:适用于 macOS 目标的视频二维码检测器
  • iOS QRCode 检测器:适用于 iOS 目标的视频二维码检测器(需要真实设备)

示例

您可以在 Demo 子目录中找到一些示例应用程序。其中包括简单的示例应用程序,用于

  • SwiftUI(macOS、iOS、macCatalyst、watchOS)
  • iOS(Swift,包括 macCatalyst)
  • macOS(Swift 和 Objective-C)

命令行工具

您可以通过打开终端窗口,使用 cd 进入 QRCode 文件夹,并使用以下命令构建命令行工具:

swift build -c release --product qrcodegen

qrcodegen 工具位于 .build/release 文件夹中。

% .build/debug/qrcodegen -h
OVERVIEW: Create a qr code

Examples:
   qrcodegen -t "This is a QR code" --output-file "fish.png" 512
   qrcodegen -t "QRCode on the clipboard" --output-format clipboard 1024
   qrcodegen --style-template-file qrtemplate.json -t "QRCode on the clipboard" --output-format clipboard 1024

* If you don't specify either -t or --input-file, the qrcode content will be read from STDIN
* If you don't specify an output file, the generated qr code will be written to a temporary file
  and opened in the default application.

USAGE: qr-code-gen [<options>] <dimension>

ARGUMENTS:
  <dimension>             The QR code dimension. 

OPTIONS:
  --input-file <input-file>
                          The file containing the content for the QR code 
  --output-file <output-file>
                          The output file 
  --output-format <output-format>
                          The output format (png [default],pdf,svg,ascii,smallascii,clipboard) 
  --output-compression <output-compression>
                          The output format compression factor (if the output format supports it, png,jpg) 
  --style-template-file <style-template-file>
                          The QR code file to use as a style template 
  -t, --text <text>       The text to be stored in the QR code 
  -s, --silence           Silence any output 
  -c, --error-correction <error-correction>
                          The level of error correction. Available levels are "L" (low), "M" (medium), "Q" (quantize),
                          "H" (high) 
  -p, --pupil-shape <pupil-shape>
                          The pupil shape to use. Available shapes are barsHorizontal, barsVertical, circle,
                          corneredPixels, leaf, pixels, roundedOuter, roundedPointingIn, roundedPointingOut,
                          roundedRect, square, squircle. 
  -e, --eye-shape <eye-shape>
                          The eye shape to use. Available shapes are barsHorizontal, barsVertical, circle,
                          corneredPixels, leaf, pixels, roundedOuter, roundedPointingIn, roundedPointingOut,
                          roundedRect, square, squircle. 
  -d, --on-pixel-shape <on-pixel-shape>
                          The onPixels shape to use. Available shapes are circle, curvePixel, horizontal, pointy,
                          roundedPath, roundedRect, sharp, square, squircle, vertical. 
  -n, --inset-fraction <inset-fraction>
                          The spacing around each individual pixel in the onPixels section 
  -r, --on-pixel-shape-corner-radius <on-pixel-shape-corner-radius>
                          The onPixels shape corner radius fractional value (0.0 -> 1.0) 
  --bg-color <bg-color>   The background color to use (format r,g,b,a - 1.0,0.5,0.5,1.0) 
  --data-color <data-color>
                          The onPixels color to use (format r,g,b,a - 1.0,0.5,0.5,1.0) 
  --eye-color <eye-color> The eye color to use (format r,g,b,a - 1.0,0.5,0.5,1.0) 
  --pupil-color <pupil-color>
                          The pupil color to use (format r,g,b,a - 1.0,0.5,0.5,1.0) 
  -h, --help              Show help information.

示例

# Generate a qr code 800x800, png format, using roundedPath for the data, leaf for the eye and a transparent background
.build/release/qrcodegen -c H -d roundedPath -e leaf --bg-color 1.0,1.0,1.0,0.0 -t "qrcode generated by command line" --output-file "output.png" 800

感谢

Denso Wave

Denso Wave

二维码是DENSO WAVE的注册商标。

swift-qrcode-generator

由于watchOS不支持Core Image过滤器,我转而使用(可选的)第三方库来生成适用于watchOS的二维码。该库基于Nayuki的二维码生成器代码。

swift-qrcode-generator

许可证

QRCode

MIT License

Copyright (c) 2023 Darren Ford

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

swift-qrcode-generator

MIT License

Copyright (c) Project Nayuki. (MIT License)
Copyright (c) 2020 fwcd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.