7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

swiftでZXingを使用してバーコード、QRコードを生成する

Posted at

探したんですがObj-cしか見当たらなかった為備忘録

#何故CIFilterではないか
現在CIFilterはcode128,pdf417,aztec,qrコードしか対応していない(はず)です。

なのでCodaBar(NW-7)などの形式を作成したいとなった時は外部ライブラリを使用するしかありません。

ということでコード
CocoaPods,CarthageなどでZXingを導入しておいて下さい。

BarCodeGenerator.swift
import UIKit
import ZXingObjC

class BarCodeGenerator {

    static public func generateBarCode(from string: String) -> UIImage? {
        do {
            let writer = ZXMultiFormatWriter()
            let hints = ZXEncodeHints() as ZXEncodeHints
            let result = try writer.encode(string, format: "好きなタイプ", width: 好きな幅, height: 好きな高さ, hints: hints)
            
            if let imageRef = ZXImage.init(matrix: result) {
                if let image = imageRef.cgimage {
                    return UIImage.init(cgImage: image)
                }
            }
        }
        catch {
            print(error)
        }
        return nil
    }
}

#使用方法

let image = BarCodeGenerator.generateBarCode(from: "aaa")

#バーコードタイプ

type enum
Aztec kBarcodeFormatAztec
Codabar kBarcodeFormatCodabar
Code 39 kBarcodeFormatCode39
Code 93 kBarcodeFormatCode93
Code 128 kBarcodeFormatCode128
Data Matrix kBarcodeFormatDataMatrix
EAN-8 kBarcodeFormatEan8
EAN-13 kBarcodeFormatEan13
ITF kBarcodeFormatITF
MaxiCode kBarcodeFormatMaxiCode
PDF417 kBarcodeFormatPDF417
QRCode kBarcodeFormatQRCode
RSS14 kBarcodeFormatRSS14
RSS kBarcodeFormatRSSExpanded
UPC-A kBarcodeFormatUPCA
UPC-E kBarcodeFormatUPCE
UPC/EAN kBarcodeFormatUPCEANExtension
7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?