一个快速、时尚、美观的 macOS/iOS/tvOS/watchOS QR 码生成器/检测器库,适用于 SwiftUI、Swift 和 Objective-C。
CGPath
路径。QRCodeDetector
)。.package(url: "https://github.com/dagronf/qrcode.git", from: "20.0.0")
pod 'DSF_QRCode', '~> 20.0.0'
用于生成美观 QR 码的核心功能位于 QRCode
库中。
如果您想使用二维码视频检测,您需要导入 QRCodeDetector
库。 将它们分成两个不同的库的原因是因为视频检测**需要**您的应用在包含的应用中定义一个 NSCameraUsageDescription
(以及添加一个 AVFoundation
依赖项),如果您将其放在应用商店中 - 如果您的应用程序不需要它,您可能不希望这样做!
QRCode
QRCodeDetector
Swift:import QRCode
Objective-C:@import QRCode;
QRCode
在其核心支持 Objective-C,允许在 Swift 和 Objective-C 中使用。
虽然直接在 Xcode 中使用 QRCode
会自动支持这一点,但重要的是确保链接到 Objective-C 库。 如果没有,您在运行时将收到崩溃。
您需要确保您的链接器标志 OTHER_LDFLAGS
包含 -ObjC
例如,使用 Tuist,您需要添加以下内容...
settings: Settings(
base: [
"OTHER_LDFLAGS": "-ObjC"
],
...
)
您可以通过创建 QRCode.Document
的实例来创建 QR 码
let doc = try QRCode.Document(utf8String: "This is the content")
// Create a CGImage
let cgImage = try doc.cgImage(dimension: 400)
// Create a PNG image
let pngData = try doc.pngData(dimension: 400)
// Create a PDF (scalable content!)
let pdfData = try doc.pdfData(dimension: 400)
// Create an SVG (scalable content!)
let svgData = try doc.svgData(dimension: 400)
// Create a CGPath
let path = try doc.path(dimension: 400)
NSError* error = NULL;
QRCodeDocument* code = [[QRCodeDocument alloc] initWithUtf8String:@"This is the content"
errorCorrection:QRCodeErrorCorrectionHigh
engine:NULL
error:&error];
CGImageRef cgr = [doc cgImageWithDimension:400 error:&error];
位图 | 矢量 |
---|---|
![]() |
![]() |
@objc public var errorCorrection: QRCode.ErrorCorrection = .quantize
QRCode.Document
具有 4 个不同的编码级别
错误纠正 | 描述 |
---|---|
low | 最低错误纠正 (L - 恢复 7% 的数据) |
medium | 中等错误纠正 (M - 恢复 15% 的数据) |
quantize | 量化错误纠正 (Q - 恢复 25% 的数据) |
high | 高错误纠正 (H - 恢复 30% 的数据) |
QRCode.Document
具有许多用于生成 QR 码的方法和样式。
位图类型 | PNG 、TIFF 、JPEG |
矢量类型 | PDF 、SVG |
路径类型 | CGPath |
图像类型 | CGImage 、NSImage 、UIImage |
文本类型 | json |
let doc = QRCode.Document("This is a test")
// Setting raw data
doc.data = Data(...)
// Setting text
doc.utf8String = "This is my text"
doc.setText("This is my text")
// Setting a message
doc.setMessage(...)
错误纠正级别越高,QR 码将越大。
QRCode
支持多种“设计”QR 码的方法。 默认情况下,QR 码将以其传统形式生成 - 正方形、黑色前景和白色背景。 通过调整 QR 码的设计设置,您可以使其更漂亮一些。
You can style your QR code so much that it can no longer be read by readers.
1. Always check that your QR code can be read **at the size that it will be presented to users**. (hint: use your phone!)
2. Have good contrast between the QR Code and its background
3. If you use 'off' pixels (see below) make sure they are very high contrast to the 'on' pixels.
4. Don't have high contrast between the 'on' pixels and the eye.
设计包含两个组件:-
描述 | |
---|---|
shape | QR 码中每个单独组件的形状 |
style | QR 码中每个单独组件的填充样式 |
您可以单独指定 QR 码的每个组件的形状和填充样式。
QRCode 由四个不同的组件组成
onPixels
)eye
(眼睛的外部)和 pupil
(眼睛的内部)组成。offPixels
)一旦你有了你的 QRCode.Document
,有很多方法可以设置它的样式,让你的设计更个性化
let doc = try QRCode.Document("This is a test")
// 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 = try doc.uiImage(CGSize(width: 400, height: 400), dpi: 216)
// Generate pdf data containing the qr code
let pdfdata = try 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)
QRCode.Builder
是 QRCode Document 的一个轻量级的 Swift-only 便利 shim。
let image = try QRCode.build
.text("https://www.worldwildlife.org/about")
.quietZonePixelCount(3)
.foregroundColor(CGColor(srgbRed: 1, green: 0, blue: 0.6, alpha: 1))
.backgroundColor(CGColor(srgbRed: 0, green: 0, blue: 0.2, alpha: 1))
.background.cornerRadius(3)
.onPixels.shape(QRCode.PixelShape.CurvePixel())
.eye.shape(QRCode.EyeShape.Teardrop())
.generate.image(dimension: 600, representation: .png())
'shape' 表示绘制每个组件的方式
数据形状表示 QR 码中的“像素”的显示方式。 默认情况下,这是一个简单的正方形,但是您可以提供一个 PixelShape
对象来自定义绘制数据。 有多种样式的内置生成器。
您可以提供一个 EyeShape
对象来仅设置生成的 QR 码的眼睛样式。 有用于正方形、圆形、圆角矩形等的内置生成器。
您可以提供对默认 EyeShape
瞳孔形状的覆盖,以仅更改瞳孔的形状。 有用于正方形、圆形、圆角矩形等的内置生成器。
如果您不覆盖瞳孔形状,则默认为眼睛形状的瞳孔形状。
let doc = try 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)
您可以指定一个在数据“像素”关闭时绘制的形状。 这可以用来使你的二维码更漂亮。 请记住,您添加到 QR 码的修饰越多,就越难读取。
确保“offPixels”形状和“onPixels”形状之间存在高颜色对比度以帮助读者非常重要。
let doc1 = try 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 = try doc1.cgImage(CGSize(width: 300, height: 300))
您可以为 QR 码的任何单独组件提供自定义填充。
let doc2 = try 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 = try doc2.cgImage(CGSize(width: 300, height: 300))
该库支持当前的填充类型。
QRCode.FillStyle.Solid
)QRCode.FillStyle.LinearGradient
)QRCode.FillStyle.RadialGradient
)QRCode.FillStyle.Image
)一个带有红色径向填充的简单 QRCode。
let doc3 = try 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 = try doc3.cgImage(CGSize(width: 300, height: 300))
QRCode.Shadow
类用于将阴影应用于 QR 码。 阴影应用于 QRCode.Document
的 style
组件
添加重阴影会对识别 QR 码的内容产生严重不利影响。
阴影同样应用于 QRCode 的主要组件,即:-
.onPixels
.eye
.pupil
默认情况下,不应用阴影。
参数 | 描述 |
---|---|
dx |
沿水平轴偏移的 module 宽度的分数 (1.0 == 1 module 宽度) |
dy |
沿垂直轴偏移的 module 高度的分数 (1.0 == 1 module 高度) |
blur |
阴影的模糊半径 |
color |
阴影的颜色 |
一个 module
表示 QRCode 输出中的单个正方形。 例如,在下面的图片中,dx 和 dy 值等于 0.5。
let shadow = QRCode.Shadow(.dropShadow, dx: 0.2, dy: -0.2, blur: 3, color: CGColor.sRGBA(1, 0, 1))
document.design.style.shadow = shadow
NSColor* color = [NSColor colorWithRed: 1.0 green: 0.0 blue: 0.0 alpha: 1.0];
struct CGColor* shadowColor = [color CGColor];
QRCodeShadow* shadow = [[QRCodeShadow alloc] init:QRCodeShadowTypeDropShadow
dx: 0.2
dy: -0.2
blur: 3
color: shadowColor];
document.design.style.shadow = shadow;
let doc = try QRCode.Document(utf8String: "Drop shadow sample")
let shadow = QRCode.Shadow(
.dropShadow,
dx: 0.2,
dy: -0.2,
blur: 8,
color: CGColor.sRGBA(0, 1, 0, 1)
)
doc.design.style.shadow = shadow
let pngData = try doc.pngData(dimension: 600, dpi: 144)
let shadow = QRCode.Shadow(.innerShadow, dx: 0.2, dy: -0.2, blur: 3, color: CGColor.sRGBA(1, 0, 1))
document.design.style.shadow = shadow
let doc = try QRCode.Document(utf8String: "Inner shadow sample")
let shadow = QRCode.Shadow(
.innerShadow,
dx: 0.2,
dy: -0.2,
blur: 8,
color: CGColor.sRGBA(0, 1, 0, 1)
)
doc.design.style.shadow = shadow
let pngData = try doc.pngData(dimension: 600, dpi: 144)
QRCode.LogoTemplate
类用于定义二维码上的 Logo。该文档有一个 logoTemplate
成员,可以在其中设置 Logo(请参见以下示例)
添加 Logo 可能会严重影响识别二维码内容的能力。如果添加 Logo,强烈建议将纠错级别设置为 .high
。覆盖超过 25% 数据的 Logo 比成功的读取更容易导致失败。
添加图像后,务必验证二维码是否可以读取(大多数手机摄像头都可以读取二维码)。如果 Logo 最终覆盖了超过 25% 的数据,则您的二维码很可能在某些读取器上难以读取。在报告二维码无法读取的错误之前,请删除图像并重试。如果删除图像后可以读取代码,则意味着您的 Logo 太大。
最简单的方法是提供一个 Logo 和一个可选的透明图像遮罩。 如果未提供遮罩,该库将使用 Logo 图像中的透明度信息为您生成遮罩。
图像和遮罩图像的大小应相同且为正方形,以获得最佳效果。 Logo 和遮罩都将在应用之前缩放到二维码的最终大小。
logo | 遮罩 | 结果 | |
---|---|---|---|
![]() |
![]() |
➜ | ![]() |
let doc = try 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)
logo | 遮罩 | 结果 |
---|---|---|
![]() |
![]() |
![]() |
let doc = try 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)
logo | 结果 |
---|---|
![]() |
![]() |
Logo 模板定义一个图像以及在二维码中绘制该图像的相对路径。
相对路径表示在二维码“数据”中绘制图像的部分。它表示二维码边界内的相对路径(即 x=0.0,y=0.0,width=1.0,height=1.0)。
x=0.0,y=0.0 表示二维码的左上角。
例如,如果您想在二维码的中心放置一个圆形 Logo,且圆的大小正好是二维码的 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 大小的矩形 Logo 将是:-
let path = CGPath(rect: CGRect(x: 0.75, y: 0.75, width: 0.25, height: 0.25), transform: nil)
遮罩路径仅影响二维码中的 onPixels
和 offPixels
。 定义落在定位点边界内的Logo将被裁剪。
有许多用于“标准”Logo 位置的预构建 LogoTemplate
创建器。
QRCode.LogoTemplate.CircleCenter
)QRCode.LogoTemplate.CircleBottomRight
)QRCode.LogoTemplate.SquareCenter
)QRCode.LogoTemplate.SquareBottomRight
)// Define a rectangle mask within the bounds of the QR code. A centered square, 30% of the qr code size.
let doc = try 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 = try doc.nsImage(dimension: 300)
生成
二维码右下角的圆形 Logo
let doc = try 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 = try doc.uiImage(dimension: 300, image: image)
生成
您可以通过在设计对象上设置 additionalQuietZonePixels
来在二维码外部添加静默区。这表示实际二维码外部添加的像素间距数。
请注意,背景颜色/图像/填充不受静默区的影响(始终延伸到生成图像的边界)
默认情况下,静默区设置为 0 像素。
0 像素 | 5 像素 | 10 像素 | 15 像素 | 背景图片 6 像素 |
---|---|---|---|---|
![]() |
![]() |
![]() |
![]() |
![]() |
let doc = try QRCode.Document("https://swiftlang.cn/about/")
doc.design.style.background = QRCode.FillStyle.Solid(0.410, 1.000, 0.375)
doc.design.additionalQuietZonePixels = 4
let qrcodeImage = try doc.cgImage(CGSize(width: 300, height: 300))
您可以为样式对象上的背景填充指定一个圆角半径,该半径以分数二维码数据像素值表示。
默认情况下,圆角半径设置为 0。
0 像素 | 2 像素 | 4 像素 | 6 像素 |
---|---|---|---|
![]() |
![]() |
![]() |
![]() |
let doc = try QRCode.Document("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 = try doc.cgImage(CGSize(width: 300, height: 300))
有许多二维码数据格式在二维码读取器中相对常见,例如包含电话号码或联系方式的二维码。
有许多内置的格式化器可用于生成一些常见的二维码类型。 这些可以在 messages
子文件夹中找到。
@objc func path(_ size: CGSize, components: Components, design: QRCode.Design) -> CGPath
生成 QRCode 的 CGPath 表示形式
组件允许调用者为 QR 代码组件生成单独的路径,然后可以单独设置样式并稍后重新组合。
CGPath
上也有扩展,使得从二维码生成 CGPath
更加容易。
let qrcodePath = CGPath.qrCode("This is a test!!!", dimension: 800)
@objc func cgImage(_ size: CGSize, dpi: CGFloat = 72.0) throws -> CGImage
从 QR 代码生成 CGImage,使用(可选)设计对象来设置 QR 代码的样式
@objc func nsImage(_ size: CGSize, dpi: CGFloat = 72.0) throws -> NSImage
(仅 macOS) 从 QR 代码生成 NSImage,使用(可选)设计对象来设置 QR 代码的样式
@objc func uiImage(_ size: CGSize, dpi: CGFloat = 72.0) throws -> UIImage
(仅 iOS/tvOS/watchOS/macCatalyst) 从 QR 代码生成 UIImage,使用(可选)设计对象来设置 QR 代码的样式
@objc func pdfData(_ size: CGSize, pdfResolution: CGFloat) throws -> Data
使用(可选)设计对象和分辨率从 QRCode 生成可缩放 PDF,以设置 QR 代码的样式
@objc func svg(dimension: Int) -> String
生成 QR 代码的 SVG 表示形式。
将 QRCode 的多个表示形式添加到指定的剪贴板
平台 | 添加的类型 |
---|---|
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 代码集返回 QR 代码的 ASCII 表示形式
仅在使用固定宽度字体显示时才有意义。
@objc func smallAsciiRepresentation() -> String
使用扩展 ASCII 代码集返回 QR 代码的小型 ASCII 表示形式(大约是常规大小的 1/2)
仅在使用固定宽度字体显示时才有意义。
此库提供用于显示样式化 QR 代码的即插即用组件。
QRCodeDocumentView
是一个视图实现,用于显示 QRCode.Document
对象。
QRCodeView
是一个用于显示 QR 代码的视图实现。 此视图支持:-
@IBDesignable
,因此您可以在 Interface Builder 中完全设计和设置 QR 代码的样式,而无需 QRCode.Document
对象。将时尚的 QR 代码添加到您的 SwiftUI 应用程序的最简单方法。 QRCodeViewUI
是一个 SwiftUI 视图,用于显示仅具有基本样式元素的 qrcode。
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),
onPixelShape: QRCode.PixelShape.RoundedPath(cornerRadiusFraction: 0.7, hasInnerCorners: true),
eyeShape: QRCode.EyeShape.RoundedRect()
)
如果您需要更多地控制 QR 代码的样式和内容,则 QRCodeDocumentViewUI
是一个 SwiftUI
视图,用于显示 QRCode.Document
对象。
var body: some View {
VStack {
QRCodeDocumentUIView(document: doc)
}
.padding()
}
QRCodeShape
是一个 SwiftUI
Shape 对象,用于从 QR 代码的不同组件生成路径。
因此,您可以对任何 SwiftUI shape 对象(例如,矩形)执行的任何操作,现在都可以对样式化的 QRCode shape 轮廓执行。
例如,您可以使用 .fill
设置颜色内容(例如,线性渐变、纯色等),添加阴影、添加转换等...
let qrContent = try 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,eye,pupil)
func eyeShape(_ eyeShape: QRCodeEyeShape) -> QRCodeShape
设置定位点的形状(eye 和 pupil)
func pupilShape(_ pupilShape: QRCodePupilShape) -> QRCodeShape
设置瞳孔的形状
func onPixelShape(_ pixelShape: QRCodePixelShape) -> QRCodeShape
设置 QR 代码中“开启”像素的形状
func offPixelShape(_ pixelShape: QRCodePixelShape) -> QRCodeShape
设置 QR 代码中“关闭”像素的形状
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)
}
}
QRCode
库完全支持 Objective-C。
QRCodeDocument* doc = [QRCodeDocument new];
doc.utf8String = @"This is an objective-c qr code";
doc.design.shape.onPixels = [QRCodePixelShapeRazor new];
NSError* error = NULL;
CGImageRef image = [doc cgImageWithDimension:600 error:&error];
assert(error == nil);
QRCode* code = [[QRCode alloc] init];
[code updateWithText:@"This message"
errorCorrection:QRCodeErrorCorrectionHigh
error:nil];
// Create a new design
QRCodeDesign* design = [QRCodeDesign new];
// Set the foreground color to a solid red
design.style.onPixels = [[QRCodeFillStyleSolid alloc] init: CGColorCreateGenericRGB(1, 0, 0, 1)];
// Use the leaf style
design.shape.eye = [[QRCodeEyeShapeLeaf alloc] init];
// Generate the image
CGImageRef image = [code cgImage:CGSizeMake(400, 400)
design:design
logoTemplate:nil
error:nil];
QRCode.Document
类具有将 QRCode 定义加载/保存为 JSON 格式的方法
let qrCode = try 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)
该库提供了一种检测图像中二维码的机制
// 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.detectQRCodeStrings()
为了允许在 App Store 或 Test Flight 目标中使用 QRCode
而无需允许相机使用,视频检测器组件已被提取到其自己的目标 QRCodeDetector
中。
有一个视频检测器类 QRCodeDetector.VideoDetector
,它是一个非常基本的视频流二维码检测器。
有两个基本的演示演示了视频流中的二维码检测。
macOS QRCode Detector
:macOS 目标的视频二维码检测器iOS QRCode Detector
:iOS 目标的视频二维码检测器(需要真实设备)有许多演示应用程序,您可以在 Demo
子文件夹中找到它们。 有简单的演示应用程序
您可以通过打开终端窗口,cd
进入 QRCode 文件夹并使用以下命令构建命令行工具
swift build -c release --product qrcodegen
qrcodegen
工具可以在 .build/release
文件夹中找到。
% .build/release/qrcodegen --help
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.
* You can generate a style template file by exporting to json format.
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,json)
--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
--logo-image-file <logo-image-file>
The image file to use as a logo if the style template file defines a logo 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)
--all-pixel-shapes <all-pixel-shapes>
Print all the available pixel shapes.
-d, --on-pixel-shape <on-pixel-shape>
The onPixels shape to use. Available shapes are grid2x2, grid3x3, grid4x4, abstract, arrow, blob, crt, circle,
circuit, curvePixel, donut, flower, heart, horizontal, pointy, razor, roundedEndIndent, roundedPath, roundedRect,
sharp, shiny, spikyCircle, square, squircle, star, vertical, vortex, wave.
-n, --on-pixel-inset-fraction <on-pixel-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)
-a, --on-pixel-shape-has-inner-corners <on-pixel-shape-has-inner-corners>
The onPixels 'has inner corners' value (true/false)
--all-eye-shapes <all-eye-shapes>
Print all the available eye shapes.
-e, --eye-shape <eye-shape>
The eye shape to use. Available shapes are crt, circle, corneredPixels, dotDragHorizontal, dotDragVertical, edges,
explode, eye, fireball, headlight, barsHorizontal, leaf, peacock, pinch, pixels, roundedPointingIn, roundedOuter,
roundedRect, shield, spikyCircle, square, squarePeg, squircle, surroundingBars, teardrop, ufo, usePixelShape,
barsVertical.
--eye-shape-corner-radius <eye-shape-corner-radius>
The fractional (0 ... 1) corner radius to use for the eye shape IF the eye shape supports it.
--all-pupil-shapes <all-pupil-shapes>
Print all the available pupil shapes.
-p, --pupil-shape <pupil-shape>
The pupil shape to use. Available shapes are blade, blobby, crt, circle, corneredPixels, cross, crossCurved,
dotDragHorizontal, dotDragVertical, edges, explode, forest, hexagonLeaf, barsHorizontal, leaf, orbits, pinch, pixels,
roundedPointingIn, roundedOuter, roundedRect, seal, shield, spikyCircle, square, barsHorizontalSquare,
barsVerticalSquare, squircle, teardrop, ufo, usePixelShape, barsVertical.
--pupil-shape-corner-radius <pupil-shape-corner-radius>
The fractional (0 ... 1) corner radius to apply to the pupil shape IF the pupil shape supports it.
--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
QR Code 是 DENSO WAVE 的注册商标。
由于 watchOS 不支持 Core Image 过滤器,因此我倾向于使用(可选的)第三方来为 watchOS 生成 QR 码。 它基于Nayuki 的 QR Code 生成器代码。
MIT License
Copyright (c) 2025 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.
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.