Manos Chorianopoulos

add barcode lib

Showing 44 changed files with 1831 additions and 4 deletions
No preview for this file type
......@@ -6,5 +6,6 @@ target 'WarplySDKFrameworkIOS' do
use_frameworks!
# Pods for WarplySDKFrameworkIOS
pod 'RSBarcodes_Swift', '~> 5.1.1'
end
......
PODFILE CHECKSUM: 469e9ad6db6643e917950516ae5b80abb382aab0
PODS:
- RSBarcodes_Swift (5.1.1)
DEPENDENCIES:
- RSBarcodes_Swift (~> 5.1.1)
SPEC REPOS:
trunk:
- RSBarcodes_Swift
SPEC CHECKSUMS:
RSBarcodes_Swift: 9be8dd1d00b9ac12e72f3d853cacb680c7722c9f
PODFILE CHECKSUM: be58eb83ead1cb6b1899b4f27c75472329a24d7f
COCOAPODS: 1.11.2
......
PODFILE CHECKSUM: 469e9ad6db6643e917950516ae5b80abb382aab0
PODS:
- RSBarcodes_Swift (5.1.1)
DEPENDENCIES:
- RSBarcodes_Swift (~> 5.1.1)
SPEC REPOS:
trunk:
- RSBarcodes_Swift
SPEC CHECKSUMS:
RSBarcodes_Swift: 9be8dd1d00b9ac12e72f3d853cacb680c7722c9f
PODFILE CHECKSUM: be58eb83ead1cb6b1899b4f27c75472329a24d7f
COCOAPODS: 1.11.2
......
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1240"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "C6C64B3B320397CC1D8287CA8BA24255"
BuildableName = "Pods_WarplySDKFrameworkIOS.framework"
BlueprintName = "Pods-WarplySDKFrameworkIOS"
ReferencedContainer = "container:Pods.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1240"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "3C896FA0C00DEA19240C4BFD2C54E0D3"
BuildableName = "RSBarcodes_Swift.framework"
BlueprintName = "RSBarcodes_Swift"
ReferencedContainer = "container:Pods.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
......@@ -4,11 +4,22 @@
<dict>
<key>SchemeUserState</key>
<dict>
<key>Pods-WarplySDKFrameworkIOS.xcscheme_^#shared#^_</key>
<key>Pods-WarplySDKFrameworkIOS.xcscheme</key>
<dict>
<key>isShown</key>
<false/>
<key>orderHint</key>
<integer>0</integer>
</dict>
<key>RSBarcodes_Swift.xcscheme</key>
<dict>
<key>isShown</key>
<false/>
<key>orderHint</key>
<integer>1</integer>
</dict>
</dict>
<key>SuppressBuildableAutocreation</key>
<dict/>
</dict>
</plist>
......
The MIT License (MIT)
Copyright (c) 2012-2014 P.D.Q.
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.
<p align="center">
<img src="https://raw.githubusercontent.com/yeahdongcn/RSBarcodes_Swift/master/home-hero-swift-hero.png">
</p>
RSBarcodes, now in Swift.
[![Build Status](https://travis-ci.org/yeahdongcn/RSBarcodes_Swift.svg?branch=master)](https://travis-ci.org/yeahdongcn/RSBarcodes_Swift) [![codecov.io](https://codecov.io/gh/yeahdongcn/RSBarcodes_Swift/branch/master/graphs/badge.svg)](https://codecov.io/gh/yeahdongcn/RSBarcodes_Swift/branch/master) ![](https://img.shields.io/badge/Swift-5.0-blue.svg?style=flat) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![](https://img.shields.io/badge/license-MIT-blue.svg?style=flat)
---
RSBarcodes allows you to read 1D and 2D barcodes using the metadata scanning capabilities introduced with iOS 7 and generate the same set of barcode images for displaying and sharing. Now implemented in Swift.
- Objective-C version: [RSBarcodes](https://github.com/yeahdongcn/RSBarcodes)
## TODO
### Generators
- [x] Code39
- [x] Code39Mod43
- [x] ExtendedCode39
- [x] Code93
- [x] Code128
- [x] UPCE
- [x] EAN FAMILIY (EAN8 EAN13 ISBN13 ISSN13)
- [x] ITF14
- [x] Interleaved2of5
- [ ] DataMatrix
- [x] PDF417
- [x] QR
- [x] Aztec
- [x] Views
### Reader
- [x] Views
- [x] ReaderController
## Installation
### [Swift Package Manager](https://github.com/apple/swift-package-manager)
To add a package dependency to your Xcode project, select File > Swift Packages > Add Package Dependency and enter https://github.com/yeahdongcn/RSBarcodes_Swift to the text field.
### [CocoaPods](http://cocoapods.org)
Simply add the following lines to your `Podfile`:
```ruby
# required by Cocoapods 0.36.0.rc.1 for Swift Pods
use_frameworks!
pod 'RSBarcodes_Swift', '~> 5.1.1'
```
You will need to import RSBarcodes_Swift manually in the ViewController file after creating the file using wizard.
*(CocoaPods v0.36 or later required. See [this blog post](http://blog.cocoapods.org/Pod-Authors-Guide-to-CocoaPods-Frameworks/) for details.)*
### [Carthage](http://github.com/Carthage/Carthage)
Simply add the following line to your `Cartfile`:
```ruby
github "yeahdongcn/RSBarcodes_Swift" >= 5.1.1
```
You will need to import RSBarcodes_Swift manually in the ViewController file after creating the file using wizard.
### Swift Package Manager (required Xcode 11)
1. Select File > Swift Packages > Add Package Dependency. Enter `https://github.com/yeahdongcn/RSBarcodes_Swift` in the "Choose Package Repository" dialog.
2. In the next page, specify the version resolving rule as "Up to Next Major" with the latest version.
3. After Xcode checking out the source and resolving the version, you can choose the "RSBarcodes_Swift" library and add it to your app target.
### Manual
1. Add RSBarcodes_Swift as a [submodule](http://git-scm.com/docs/git-submodule) by opening the Terminal, `cd`-ing into your top-level project directory, and entering the command `git submodule add https://github.com/yeahdongcn/RSBarcodes_Swift.git`
2. Open the `RSBarcodes_Swift` folder, and drag `RSBarcodes.xcodeproj` into the file navigator of your app project.
3. In Xcode, navigate to the target configuration window by clicking on the blue project icon, and select the application target under the "Targets" heading in the sidebar.
4. Ensure that the deployment target of RSBarcodes.framework matches that of the application target.
5. In the tab bar at the top of that window, open the "Build Phases" panel.
6. Expand the "Target Dependencies" group, and add `RSBarcodes.framework`.
7. Click on the `+` button at the top left of the panel and select "New Copy Files Phase". Rename this new phase to "Copy Frameworks", set the "Destination" to "Frameworks", and add `RSBarcodes.framework`.
8. Need to import RSBarcodes manually in the ViewController file after creating the file using wizard.
## Usage
[How to Use Generator](#generator-1) and
[How to Use Reader](#reader-1)
### Generators
First, import the following frameworks:
``` swift
import RSBarcodes_Swift
import AVFoundation
```
Then, use the generator to generate a barcode. For example:
``` swift
RSUnifiedCodeGenerator.shared.generateCode("2166529V", machineReadableCodeObjectType: AVMetadataObjectTypeCode39Code)
```
It will generate a `UIImage` instance if the `2166529V` is a valid code39 string. For `AVMetadataObjectTypeCode128Code`, you can change `useBuiltInCode128Generator` to `false` to use my implementation (AutoTable for code128).
P.S. There are 4 tables for encoding a string to code128, `TableA`, `TableB`, `TableC` and `TableAuto`; the `TableAuto` is always the best choice, but if one has specific requirements, try this:
``` swift
RSCode128Generator(codeTable: .A).generateCode("123456", machineReadableCodeObjectType: AVMetadataObjectTypeCode128Code)
```
Example of these simple calls can be found in the test project.
### Reader
The following are steps to get the barcode reader working:
1. `File` -> `New` -> `File`
2. Under `iOS` click `source` and make sure `Cocoa Touch Class` is selected and hit `Next`.
3. Call the name of the class whatever you want but I will refer to it as `ScanViewController` from now on.
4. Make it a subclass of `RSCodeReaderViewController` and ensure the language is `Swift` and hit `Next` and then `Create`
5. Open your storyboard and drag a `UIViewController` onto it.
6. Show the identity inspect and under custom class select `ScanViewController`
7. The focus mark layer and corners layer are already there working for you. There are two handlers: one for the single tap on the screen along with the focus mark and one detected objects handler, which all detected will come to you. Now in the `ScanViewController.swift` file add the following code into the `viewDidLoad()` or some place more suitable for you:
``` swift
override func viewDidLoad() {
super.viewDidLoad()
self.focusMarkLayer.strokeColor = UIColor.red.cgColor
self.cornersLayer.strokeColor = UIColor.yellow.cgColor
self.tapHandler = { point in
print(point)
}
self.barcodesHandler = { barcodes in
for barcode in barcodes {
print("Barcode found: type=" + barcode.type + " value=" + barcode.stringValue)
}
}
}
```
If you want to ignore some code types (for example, `AVMetadataObjectTypeQRCode`), add the following lines:
``` swift
let types = NSMutableArray(array: self.output.availableMetadataObjectTypes)
types.remove(AVMetadataObjectTypeQRCode)
self.output.metadataObjectTypes = NSArray(array: types)
```
### Validator
To validate codes:
``` swift
let isValid = RSUnifiedCodeValidator.shared.isValid(code, machineReadableCodeObjectType: AVMetadataObjectTypeEAN13Code)
```
### Image helpers
Use `RSAbstractCodeGenerator.resizeImage(source: UIImage, scale: CGFloat)` to scale the generated image.
Use `RSAbstractCodeGenerator.resizeImage(source: UIImage, targetSize: CGSize, contentMode: UIViewContentMode)` to fill/fit the bounds of something to the best capability and don't necessarily know what scale is too much to fill/fit, or if the `UIImageView` itself is flexible.
## Miscellaneous
[The Swift Programming Language 中文版](https://github.com/numbbbbb/the-swift-programming-language-in-chinese/)
[Online version](http://numbbbbb.github.io/the-swift-programming-language-in-chinese/) generated using [GitBook](https://www.gitbook.io/)
## License
The MIT License (MIT)
Copyright (c) 2012-2014 P.D.Q.
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.
//
// ContextMaker.swift
// RSBarcodes
//
// Created by Alexey Korolev on 11.10.2019.
// Copyright © 2019 P.D.Q. All rights reserved.
//
import UIKit
final class ContextMaker {
static func make() -> CIContext {
return CIContext(options: nil)
}
}
//
// RSCode39Generator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/10/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import Foundation
let CODE39_ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%*"
// http://www.barcodesymbols.com/code39.htm
// http://www.barcodeisland.com/code39.phtml
open class RSCode39Generator: RSAbstractCodeGenerator {
let CODE39_CHARACTER_ENCODINGS = [
"1010011011010",
"1101001010110",
"1011001010110",
"1101100101010",
"1010011010110",
"1101001101010",
"1011001101010",
"1010010110110",
"1101001011010",
"1011001011010",
"1101010010110",
"1011010010110",
"1101101001010",
"1010110010110",
"1101011001010",
"1011011001010",
"1010100110110",
"1101010011010",
"1011010011010",
"1010110011010",
"1101010100110",
"1011010100110",
"1101101010010",
"1010110100110",
"1101011010010",
"1011011010010",
"1010101100110",
"1101010110010",
"1011010110010",
"1010110110010",
"1100101010110",
"1001101010110",
"1100110101010",
"1001011010110",
"1100101101010",
"1001101101010",
"1001010110110",
"1100101011010",
"1001101011010",
"1001001001010",
"1001001010010",
"1001010010010",
"1010010010010",
"1001011011010"
]
func encodeCharacterString(_ characterString:String) -> String {
let location = CODE39_ALPHABET_STRING.location(characterString)
return CODE39_CHARACTER_ENCODINGS[location]
}
// MAKR: RSAbstractCodeGenerator
override open func isValid(_ contents: String) -> Bool {
if contents.length() > 0
&& contents.range(of: "*") == nil
&& contents == contents.uppercased() {
for character in contents {
let location = CODE39_ALPHABET_STRING.location(String(character))
if location == NSNotFound {
return false
}
}
return true
}
return false
}
override open func initiator() -> String {
return self.encodeCharacterString("*")
}
override open func terminator() -> String {
return self.encodeCharacterString("*")
}
override open func barcode(_ contents: String) -> String {
var barcode = ""
for character in contents {
barcode += self.encodeCharacterString(String(character))
}
return barcode
}
}
//
// RSCode39Mod43Generator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/10/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
// http://www.barcodesymbols.com/code39.htm
// http://www.barcodeisland.com/code39.phtml
open class RSCode39Mod43Generator: RSCode39Generator, RSCheckDigitGenerator {
// MARK: RSAbstractCodeGenerator
override open func barcode(_ contents: String) -> String {
return super.barcode(contents + self.checkDigit(contents.uppercased()))
}
// MARK: RSCheckDigitGenerator
open func checkDigit(_ contents: String) -> String {
/**
Step 1: From the table below, find the values of each character.
C O D E 3 9 <--Message characters
12 24 13 14 38 3 9 <--Character values
Step 2: Sum the character values.
12 + 24 + 13 + 14 + 38 + 3 + 9 = 113
Step 3: Divide the result by 43.
113 / 43 = 11 with remainder of 27.
Step 4: From the table, find the character with this value.
27 = R = Check Character
*/
var sum = 0
for character in contents {
sum += CODE39_ALPHABET_STRING.location(String(character))
}
// 43 = CODE39_ALPHABET_STRING's length - 1 -- excludes asterisk
return CODE39_ALPHABET_STRING[sum % (CODE39_ALPHABET_STRING.length() - 1)]
}
}
//
// RSCode93Generator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/11/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
// http://www.barcodeisland.com/code93.phtml
open class RSCode93Generator: RSAbstractCodeGenerator, RSCheckDigitGenerator {
let CODE93_ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*"
let CODE93_PLACEHOLDER_STRING = "abcd";
let CODE93_CHARACTER_ENCODINGS = [
"100010100",
"101001000",
"101000100",
"101000010",
"100101000",
"100100100",
"100100010",
"101010000",
"100010010",
"100001010",
"110101000",
"110100100",
"110100010",
"110010100",
"110010010",
"110001010",
"101101000",
"101100100",
"101100010",
"100110100",
"100011010",
"101011000",
"101001100",
"101000110",
"100101100",
"100010110",
"110110100",
"110110010",
"110101100",
"110100110",
"110010110",
"110011010",
"101101100",
"101100110",
"100110110",
"100111010",
"100101110",
"111010100",
"111010010",
"111001010",
"101101110",
"101110110",
"110101110",
"100100110",
"111011010",
"111010110",
"100110010",
"101011110"
]
func encodeCharacterString(_ characterString:String) -> String {
return CODE93_CHARACTER_ENCODINGS[CODE93_ALPHABET_STRING.location(characterString)]
}
override open func isValid(_ contents: String) -> Bool {
if contents.length() > 0 && contents == contents.uppercased() {
for i in 0..<contents.length() {
if CODE93_ALPHABET_STRING.location(contents[i]) == NSNotFound {
return false
}
if CODE93_PLACEHOLDER_STRING.location(contents[i]) != NSNotFound {
return false
}
}
return true
}
return false
}
override open func initiator() -> String {
return self.encodeCharacterString("*")
}
override open func terminator() -> String {
// With the termination bar: 1
return self.encodeCharacterString("*") + "1"
}
override open func barcode(_ contents: String) -> String {
var barcode = ""
for character in contents {
barcode += self.encodeCharacterString(String(character))
}
let checkDigits = self.checkDigit(contents)
for character in checkDigits {
barcode += self.encodeCharacterString(String(character))
}
return barcode
}
// MARK: RSCheckDigitGenerator
open func checkDigit(_ contents: String) -> String {
// Weighted sum += value * weight
// The first character
var sum = 0
for i in 0..<contents.length() {
if let character = contents[contents.length() - i - 1] {
let characterValue = CODE93_ALPHABET_STRING.location(character)
sum += characterValue * (i % 20 + 1)
}
}
var checkDigits = ""
checkDigits += CODE93_ALPHABET_STRING[sum % 47]
// The second character
sum = 0
let newContents = contents + checkDigits
for i in 0..<newContents.length() {
if let character = newContents[newContents.length() - i - 1] {
let characterValue = CODE93_ALPHABET_STRING.location(character)
sum += characterValue * (i % 15 + 1)
}
}
checkDigits += CODE93_ALPHABET_STRING[sum % 47]
return checkDigits
}
}
//
// RSCodeDataMatrixGenerator.swift
// RSBarcodes
//
// Created by R0CKSTAR on 15/10/26.
// Copyright (c) 2015 P.D.Q. All rights reserved.
//
import UIKit
class RSCodeDataMatrixGenerator: RSAbstractCodeGenerator {
}
//
// RSCodeLayer.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/13/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
import QuartzCore
open class RSCodeLayer: CALayer {
@objc var code: UIImage?
override open func draw(in ctx: CGContext) {
if let code = self.code {
ctx.saveGState()
ctx.draw(code.cgImage!, in: self.bounds)
ctx.restoreGState()
}
}
}
//
// RSCornersLayer.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/13/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
import QuartzCore
open class RSCornersLayer: CALayer {
@objc open var strokeColor = UIColor.green.cgColor
@objc open var strokeWidth: CGFloat = 2
@objc open var drawingCornersArray: Array<Array<CGPoint>> = []
@objc open var cornersArray: Array<[Any]> = [] {
willSet {
DispatchQueue.main.async(execute: {
self.setNeedsDisplay()
})
}
}
override open func draw(in ctx: CGContext) {
guard let cornerPointsArray = cornersArray as? [[CGPoint]] else { return }
objc_sync_enter(self)
ctx.saveGState()
ctx.setShouldAntialias(true)
ctx.setAllowsAntialiasing(true)
ctx.setFillColor(UIColor.clear.cgColor)
ctx.setStrokeColor(self.strokeColor)
ctx.setLineWidth(self.strokeWidth)
for corners in cornerPointsArray {
for (idx, point) in corners.enumerated() {
if idx == 0 {
ctx.move(to: point)
} else {
ctx.addLine(to: point)
}
}
ctx.closePath()
}
ctx.drawPath(using: CGPathDrawingMode.fillStroke)
ctx.restoreGState()
objc_sync_exit(self)
}
}
//
// RSEANGenerator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/11/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
public let RSBarcodesTypeISBN13Code = "com.pdq.rsbarcodes.isbn13"
public let RSBarcodesTypeISSN13Code = "com.pdq.rsbarcodes.issn13"
// http://blog.sina.com.cn/s/blog_4015406e0100bsqk.html
open class RSEANGenerator: RSAbstractCodeGenerator {
var length = 0
// 'O' for odd and 'E' for even
let lefthandParities = [
"OOOOOO",
"OOEOEE",
"OOEEOE",
"OOEEEO",
"OEOOEE",
"OEEOOE",
"OEEEOO",
"OEOEOE",
"OEOEEO",
"OEEOEO"
]
// 'R' for right-hand
let parityEncodingTable = [
["O" : "0001101", "E" : "0100111", "R" : "1110010"],
["O" : "0011001", "E" : "0110011", "R" : "1100110"],
["O" : "0010011", "E" : "0011011", "R" : "1101100"],
["O" : "0111101", "E" : "0100001", "R" : "1000010"],
["O" : "0100011", "E" : "0011101", "R" : "1011100"],
["O" : "0110001", "E" : "0111001", "R" : "1001110"],
["O" : "0101111", "E" : "0000101", "R" : "1010000"],
["O" : "0111011", "E" : "0010001", "R" : "1000100"],
["O" : "0110111", "E" : "0001001", "R" : "1001000"],
["O" : "0001011", "E" : "0010111", "R" : "1110100"]
]
init(length:Int) {
self.length = length
}
override open func isValid(_ contents: String) -> Bool {
if super.isValid(contents) && self.length == contents.length() {
var sum_odd = 0
var sum_even = 0
for i in 0..<(self.length - 1) {
let digit = Int(contents[i])!
if i % 2 == (self.length == 13 ? 0 : 1) {
sum_even += digit
} else {
sum_odd += digit
}
}
let checkDigit = (10 - (sum_even + sum_odd * 3) % 10) % 10
return Int(contents[contents.length() - 1]) == checkDigit
}
return false
}
override open func initiator() -> String {
return "101"
}
override open func terminator() -> String {
return "101"
}
func centerGuardPattern() -> String {
return "01010"
}
override open func barcode(_ contents: String) -> String {
var lefthandParity = "OOOO"
var newContents = contents
if self.length == 13 {
lefthandParity = self.lefthandParities[Int(contents[0])!]
newContents = contents.substring(1, length: contents.length() - 1)
}
var barcode = ""
for i in 0..<newContents.length() {
let digit = Int(newContents[i])!
if i < lefthandParity.length() {
barcode += self.parityEncodingTable[digit][lefthandParity[i]]!
if i == lefthandParity.length() - 1 {
barcode += self.centerGuardPattern()
}
} else {
barcode += self.parityEncodingTable[digit]["R"]!
}
}
return barcode
}
}
class RSEAN8Generator: RSEANGenerator {
init() {
super.init(length: 8)
}
}
class RSEAN13Generator: RSEANGenerator {
init() {
super.init(length: 13)
}
}
class RSISBN13Generator: RSEAN13Generator {
override func isValid(_ contents: String) -> Bool {
// http://www.appsbarcode.com/ISBN.php
return super.isValid(contents) && contents.substring(0, length: 3) == "978"
}
}
class RSISSN13Generator: RSEAN13Generator {
override func isValid(_ contents: String) -> Bool {
// http://www.appsbarcode.com/ISSN.php
return super.isValid(contents) && contents.substring(0, length: 3) == "977"
}
}
//
// RSExtendedCode39Generator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/11/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
public let RSBarcodesTypeExtendedCode39Code = "com.pdq.rsbarcodes.code39.ext"
// http://www.barcodesymbols.com/code39.htm
// http://www.barcodeisland.com/code39.phtml
open class RSExtendedCode39Generator: RSCode39Generator {
func encodeContents(_ contents: String) -> String {
var encodedContents = ""
for character in contents {
let characterString = String(character)
switch characterString {
case "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z":
encodedContents += "+" + characterString.uppercased()
case "!":
encodedContents += "/A"
case "\"":
encodedContents += "/B"
case "#":
encodedContents += "/C"
case "$":
encodedContents += "/D"
case "%":
encodedContents += "/E"
case "&":
encodedContents += "/F"
case "'":
encodedContents += "/G"
case "(":
encodedContents += "/H"
case ")":
encodedContents += "/I"
case "*":
encodedContents += "/J"
case "+":
encodedContents += "/K"
case ",":
encodedContents += "/L"
// - -> /M better to use -
// . -> /N better to use .
case "/":
encodedContents += "/O"
// 0 -> /P better to use 0
// 1 -> /Q better to use 1
// 2 -> /R better to use 2
// 3 -> /S better to use 3
// 4 -> /T better to use 4
// 5 -> /U better to use 5
// 6 -> /V better to use 6
// 7 -> /W better to use 7
// 8 -> /X better to use 8
// 9 -> /Y better to use 9
case ":":
encodedContents += "/Z"
// ESC -> %A
// FS -> %B
// GS -> %C
// RS -> %D
// US -> %E
case ";":
encodedContents += "%F"
case "<":
encodedContents += "%G"
case "=":
encodedContents += "%H"
case ">":
encodedContents += "%I"
case "?":
encodedContents += "%J"
case "[":
encodedContents += "%K"
case "\\":
encodedContents += "%L"
case "]":
encodedContents += "%M"
case "^":
encodedContents += "%N"
case "_":
encodedContents += "%O"
case "{":
encodedContents += "%P"
case "|":
encodedContents += "%Q"
case "}":
encodedContents += "%R"
case "~":
encodedContents += "%S"
// DEL -> %T
// NUL -> %U
case "@":
encodedContents += "%V"
case "`":
encodedContents += "%W"
// SOH -> $A
// STX -> $B
// ETX -> $C
// EOT -> $D
// ENQ -> $E
// ACK -> $F
// BEL -> $G
// BS -> $H
case "\t":
encodedContents += "$I"
// LF -> $J
// VT -> $K
// FF -> $L
case "\n":
encodedContents += "$M"
// SO -> $N
// SI -> $O
// DLE -> $P
// DC1 -> $Q
// DC2 -> $R
// DC3 -> $S
// DC4 -> $T
// NAK -> $U
// SYN -> $V
// ETB -> $W
// CAN -> $X
// EM -> $Y
// SUB -> $Z
default:
encodedContents += characterString
}
}
return encodedContents
}
override open func isValid(_ contents: String) -> Bool {
if contents.length() > 0 {
let encContents = self.encodeContents(contents)
for character in encContents {
let location = CODE39_ALPHABET_STRING.location(String(character))
if location == NSNotFound {
return false
}
}
return true
}
return false
}
override open func barcode(_ contents: String) -> String {
return super.barcode(self.encodeContents(contents))
}
}
//
// RSFocusMarkLayer.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/13/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
import QuartzCore
open class RSFocusMarkLayer: CALayer {
// Use camera.app's focus mark size as default
@objc open var size = CGSize(width: 76, height: 76)
// Use camera.app's focus mark sight as default
@objc open var sight: CGFloat = 6
// Use camera.app's focus mark color as default
@objc open var strokeColor = UIColor("#ffcc00").cgColor
@objc open var strokeWidth: CGFloat = 1
@objc open var delay: CFTimeInterval = 1
@objc open var canDraw = false
@objc open var point : CGPoint = CGPoint(x: 0, y: 0) {
didSet {
DispatchQueue.main.async(execute: {
self.canDraw = true
self.setNeedsDisplay()
})
let when = DispatchTime.now() + Double(Int64(self.delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: when, execute: {
self.canDraw = false
self.setNeedsDisplay()
})
}
}
override open func draw(in ctx: CGContext) {
if !self.canDraw {
return
}
ctx.saveGState()
ctx.setShouldAntialias(true)
ctx.setAllowsAntialiasing(true)
ctx.setFillColor(UIColor.clear.cgColor)
ctx.setStrokeColor(self.strokeColor)
ctx.setLineWidth(self.strokeWidth)
// Rect
ctx.stroke(CGRect(x: self.point.x - self.size.width / 2.0, y: self.point.y - self.size.height / 2.0, width: self.size.width, height: self.size.height))
// Focus
for i in 0..<4 {
var endPoint: CGPoint
switch i {
case 0:
ctx.move(to: CGPoint(x: self.point.x, y: self.point.y - self.size.height / 2.0))
endPoint = CGPoint(x: self.point.x, y: self.point.y - self.size.height / 2.0 + self.sight)
case 1:
ctx.move(to: CGPoint(x: self.point.x, y: self.point.y + self.size.height / 2.0))
endPoint = CGPoint(x: self.point.x, y: self.point.y + self.size.height / 2.0 - self.sight)
case 2:
ctx.move(to: CGPoint(x: self.point.x - self.size.width / 2.0, y: self.point.y))
endPoint = CGPoint(x: self.point.x - self.size.width / 2.0 + self.sight, y: self.point.y)
case 3:
ctx.move(to: CGPoint(x: self.point.x + self.size.width / 2.0, y: self.point.y))
endPoint = CGPoint(x: self.point.x + self.size.width / 2.0 - self.sight, y: self.point.y)
default:
endPoint = CGPoint(x: 0, y: 0)
}
ctx.addLine(to: CGPoint(x: endPoint.x, y: endPoint.y))
}
ctx.drawPath(using: CGPathDrawingMode.fillStroke)
ctx.restoreGState()
}
}
//
// RSITF14Generator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/13/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
// http://www.gs1au.org/assets/documents/info/user_manuals/barcode_technical_details/ITF_14_Barcode_Structure.pdf
// http://www.barcodeisland.com/int2of5.phtml
open class RSITF14Generator: RSITFGenerator {
override open func isValid(_ contents: String) -> Bool {
return super.isValid(contents) && contents.length() == 14
}
}
//
// RSITFGenerator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/11/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
// http://www.barcodeisland.com/int2of5.phtml
open class RSITFGenerator: RSAbstractCodeGenerator {
let ITF_CHARACTER_ENCODINGS = [
"00110",
"10001",
"01001",
"11000",
"00101",
"10100",
"01100",
"00011",
"10010",
"01010",
]
override open func isValid(_ contents: String) -> Bool {
return super.isValid(contents) && contents.length() % 2 == 0
}
override open func initiator() -> String {
return "1010"
}
override open func terminator() -> String {
return "1101"
}
override open func barcode(_ contents: String) -> String {
var barcode = ""
for i in 0..<contents.length() / 2 {
if let pair = contents.substring(i * 2, length: 2) {
let bars = ITF_CHARACTER_ENCODINGS[Int(pair[0])!]
let spaces = ITF_CHARACTER_ENCODINGS[Int(pair[1])!]
for j in 0..<10 {
if j % 2 == 0 {
let bar = Int(bars[j / 2])
if bar == 1 {
barcode += "11"
} else {
barcode += "1"
}
} else {
let space = Int(spaces[j / 2])
if space == 1 {
barcode += "00"
} else {
barcode += "0"
}
}
}
}
}
return barcode
}
}
//
// RSUPCEGenerator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/11/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
// http://www.sly.com.tw/skill/know/new_page_6.htm
// http://mdn.morovia.com/kb/UPCE-Specification-10634.html
// http://mdn.morovia.com/kb/UPCA-Specification-10632.html
// http://www.barcodeisland.com/upce.phtml
open class RSUPCEGenerator: RSAbstractCodeGenerator, RSCheckDigitGenerator {
let UPCE_ODD_ENCODINGS = [
"0001101",
"0011001",
"0010011",
"0111101",
"0100011",
"0110001",
"0101111",
"0111011",
"0110111",
"0001011"
]
let UPCE_EVEN_ENCODINGS = [
"0100111",
"0110011",
"0011011",
"0100001",
"0011101",
"0111001",
"0000101",
"0010001",
"0001001",
"0010111"
]
let UPCE_SEQUENCES = [
"000111",
"001011",
"001101",
"001110",
"010011",
"011001",
"011100",
"010101",
"010110",
"011010"
]
func convert2UPC_A(_ contents:String) -> String {
var upc_a = ""
if let code = contents.substring(1, length: contents.length() - 2) {
let lastDigit = Int(code[code.length() - 1])!
var insertDigits = "0000"
switch lastDigit {
case 0...2:
upc_a += code.substring(0, length: 2) + String(lastDigit) + insertDigits + code.substring(2, length: 3)
case 3:
insertDigits = "00000"
upc_a += code.substring(0, length: 3) + insertDigits + code.substring(3, length: 2)
case 4:
insertDigits = "00000"
upc_a += code.substring(0, length: 4) + insertDigits + code.substring(4, length: 1)
default:
upc_a += code.substring(0, length: 5) + insertDigits + String(lastDigit)
}
}
return "00" + upc_a
}
override open func isValid(_ contents: String) -> Bool {
return super.isValid(contents)
&& contents.length() == 8
&& Int(contents[0])! == 0
&& contents[contents.length() - 1] == self.checkDigit(contents)
}
override open func initiator() -> String {
return "101"
}
override open func terminator() -> String {
return "010101"
}
override open func barcode(_ contents: String) -> String {
let checkValue = Int(contents[contents.length() - 1])!
let sequence = UPCE_SEQUENCES[checkValue]
var barcode = ""
for i in 1..<contents.length() - 1 {
let digit = Int(contents[i])!
if Int(sequence[i - 1])! % 2 == 0 {
barcode += UPCE_EVEN_ENCODINGS[digit]
} else {
barcode += UPCE_ODD_ENCODINGS[digit]
}
}
return barcode
}
// MARK: RSCheckDigitGenerator
open func checkDigit(_ contents: String) -> String {
/*
UPC-A check digit is calculated using standard Mod10 method. Here outlines the steps to calculate UPC-A check digit:
From the right to left, start with odd position, assign the odd/even position to each digit.
Sum all digits in odd position and multiply the result by 3.
Sum all digits in even position.
Sum the results of step 3 and step 4.
divide the result of step 4 by 10. The check digit is the number which adds the remainder to 10.
If there is no remainder then the check digit equals zero.
*/
let upc_a = self.convert2UPC_A(contents)
var sum_odd = 0
var sum_even = 0
for i in 0..<upc_a.length() {
let digit = Int(upc_a[i])!
if i % 2 == 0 {
sum_even += digit
} else {
sum_odd += digit
}
}
let remainder = (sum_even + sum_odd * 3) % 10
return String(remainder == 0 ? remainder : 10 - remainder)
}
}
//
// RSUnifiedCodeGenerator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/10/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import Foundation
import UIKit
import AVFoundation
open class RSUnifiedCodeGenerator: RSCodeGenerator {
open var isBuiltInCode128GeneratorSelected = false
open var fillColor: UIColor = UIColor.white
open var strokeColor: UIColor = UIColor.black
open class var shared: RSUnifiedCodeGenerator {
return UnifiedCodeGeneratorSharedInstance
}
// MARK: RSCodeGenerator
open func isValid(_ contents: String) -> Bool {
print("Use RSUnifiedCodeValidator.shared.isValid(contents:String, machineReadableCodeObjectType: String) instead")
return false
}
open func generateCode(_ contents: String, inputCorrectionLevel: InputCorrectionLevel, machineReadableCodeObjectType: String, targetSize: CGSize? = nil) -> UIImage? {
var codeGenerator: RSCodeGenerator?
switch machineReadableCodeObjectType {
case AVMetadataObject.ObjectType.qr.rawValue, AVMetadataObject.ObjectType.pdf417.rawValue, AVMetadataObject.ObjectType.aztec.rawValue:
return RSAbstractCodeGenerator.generateCode(contents, inputCorrectionLevel: inputCorrectionLevel, filterName: RSAbstractCodeGenerator.filterName(machineReadableCodeObjectType), targetSize: targetSize, fillColor: fillColor, strokeColor: strokeColor)
case AVMetadataObject.ObjectType.code39.rawValue:
codeGenerator = RSCode39Generator()
case AVMetadataObject.ObjectType.code39Mod43.rawValue:
codeGenerator = RSCode39Mod43Generator()
case AVMetadataObject.ObjectType.ean8.rawValue:
codeGenerator = RSEAN8Generator()
case AVMetadataObject.ObjectType.ean13.rawValue:
codeGenerator = RSEAN13Generator()
case AVMetadataObject.ObjectType.interleaved2of5.rawValue:
codeGenerator = RSITFGenerator()
case AVMetadataObject.ObjectType.itf14.rawValue:
codeGenerator = RSITF14Generator()
case AVMetadataObject.ObjectType.upce.rawValue:
codeGenerator = RSUPCEGenerator()
case AVMetadataObject.ObjectType.code93.rawValue:
codeGenerator = RSCode93Generator()
// iOS 8 included, but my implementation's performance is better :)
case AVMetadataObject.ObjectType.code128.rawValue:
if self.isBuiltInCode128GeneratorSelected {
return RSAbstractCodeGenerator.generateCode(contents, inputCorrectionLevel: inputCorrectionLevel, filterName: RSAbstractCodeGenerator.filterName(machineReadableCodeObjectType), targetSize: targetSize, fillColor: fillColor, strokeColor: strokeColor)
} else {
codeGenerator = RSCode128Generator()
}
case AVMetadataObject.ObjectType.dataMatrix.rawValue:
codeGenerator = RSCodeDataMatrixGenerator()
case RSBarcodesTypeISBN13Code:
codeGenerator = RSISBN13Generator()
case RSBarcodesTypeISSN13Code:
codeGenerator = RSISSN13Generator()
case RSBarcodesTypeExtendedCode39Code:
codeGenerator = RSExtendedCode39Generator()
default:
print("No code generator selected.")
}
if codeGenerator != nil {
codeGenerator!.fillColor = self.fillColor
codeGenerator!.strokeColor = self.strokeColor
return codeGenerator!.generateCode(contents, inputCorrectionLevel: inputCorrectionLevel, machineReadableCodeObjectType: machineReadableCodeObjectType, targetSize: targetSize)
} else {
return nil
}
}
open func generateCode(_ contents: String, machineReadableCodeObjectType: String, targetSize: CGSize? = nil) -> UIImage? {
return self.generateCode(contents, inputCorrectionLevel: .Medium, machineReadableCodeObjectType: machineReadableCodeObjectType, targetSize: targetSize)
}
open func generateCode(_ machineReadableCodeObject: AVMetadataMachineReadableCodeObject, inputCorrectionLevel: InputCorrectionLevel, targetSize: CGSize? = nil) -> UIImage? {
return self.generateCode(machineReadableCodeObject.stringValue!, inputCorrectionLevel: inputCorrectionLevel, machineReadableCodeObjectType: machineReadableCodeObject.type.rawValue, targetSize: targetSize)
}
open func generateCode(_ machineReadableCodeObject: AVMetadataMachineReadableCodeObject, targetSize: CGSize? = nil) -> UIImage? {
return self.generateCode(machineReadableCodeObject, inputCorrectionLevel: .Medium, targetSize: targetSize)
}
}
let UnifiedCodeGeneratorSharedInstance = RSUnifiedCodeGenerator()
//
// RSUnifiedCodeValidator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 10/3/16.
// Copyright (c) 2016 P.D.Q. All rights reserved.
//
import Foundation
import AVFoundation
open class RSUnifiedCodeValidator {
open class var shared: RSUnifiedCodeValidator {
return UnifiedCodeValidatorSharedInstance
}
open func isValid(_ contents:String, machineReadableCodeObjectType: String) -> Bool {
var codeGenerator: RSCodeGenerator?
switch machineReadableCodeObjectType {
case AVMetadataObject.ObjectType.qr.rawValue, AVMetadataObject.ObjectType.pdf417.rawValue, AVMetadataObject.ObjectType.aztec.rawValue:
return false
case AVMetadataObject.ObjectType.code39.rawValue:
codeGenerator = RSCode39Generator()
case AVMetadataObject.ObjectType.code39Mod43.rawValue:
codeGenerator = RSCode39Mod43Generator()
case AVMetadataObject.ObjectType.ean8.rawValue:
codeGenerator = RSEAN8Generator()
case AVMetadataObject.ObjectType.ean13.rawValue:
codeGenerator = RSEAN13Generator()
case AVMetadataObject.ObjectType.interleaved2of5.rawValue:
codeGenerator = RSITFGenerator()
case AVMetadataObject.ObjectType.itf14.rawValue:
codeGenerator = RSITF14Generator()
case AVMetadataObject.ObjectType.upce.rawValue:
codeGenerator = RSUPCEGenerator()
case AVMetadataObject.ObjectType.code93.rawValue:
codeGenerator = RSCode93Generator()
case AVMetadataObject.ObjectType.code128.rawValue:
codeGenerator = RSCode128Generator()
case AVMetadataObject.ObjectType.dataMatrix.rawValue:
codeGenerator = RSCodeDataMatrixGenerator()
case RSBarcodesTypeISBN13Code:
codeGenerator = RSISBN13Generator()
case RSBarcodesTypeISSN13Code:
codeGenerator = RSISSN13Generator()
case RSBarcodesTypeExtendedCode39Code:
codeGenerator = RSExtendedCode39Generator()
default:
print("No code generator selected.")
return false
}
return codeGenerator!.isValid(contents)
}
}
let UnifiedCodeValidatorSharedInstance = RSUnifiedCodeValidator()
//
// Ext.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/10/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
extension String {
func length() -> Int {
return self.count
}
func trim() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
func substring(_ location:Int, length:Int) -> String! {
return (self as NSString).substring(with: NSMakeRange(location, length))
}
subscript(index: Int) -> String! {
get {
return self.substring(index, length: 1)
}
}
func location(_ other: String) -> Int {
return (self as NSString).range(of: other).location
}
func contains(_ other: String) -> Bool {
return (self as NSString).contains(other)
}
// http://stackoverflow.com/questions/6644004/how-to-check-if-nsstring-is-contains-a-numeric-value
func isNumeric() -> Bool {
return (self as NSString).rangeOfCharacter(from: CharacterSet.decimalDigits.inverted).location == NSNotFound
}
}
//
// UIColorExtension.swift
// HEXColor
//
// Created by R0CKSTAR on 6/13/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
/**
MissingHashMarkAsPrefix: "Invalid RGB string, missing '#' as prefix"
UnableToScanHexValue: "Scan hex error"
MismatchedHexStringLength: "Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8"
*/
public enum UIColorInputError : Error {
case missingHashMarkAsPrefix,
unableToScanHexValue,
mismatchedHexStringLength
}
extension UIColor {
/**
The shorthand three-digit hexadecimal representation of color.
#RGB defines to the color #RRGGBB.
- parameter hex3: Three-digit hexadecimal value.
- parameter alpha: 0.0 - 1.0. The default is 1.0.
*/
@objc public convenience init(hex3: UInt16, alpha: CGFloat = 1) {
let divisor = CGFloat(15)
let red = CGFloat((hex3 & 0xF00) >> 8) / divisor
let green = CGFloat((hex3 & 0x0F0) >> 4) / divisor
let blue = CGFloat( hex3 & 0x00F ) / divisor
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
/**
The shorthand four-digit hexadecimal representation of color with alpha.
#RGBA defines to the color #RRGGBBAA.
- parameter hex4: Four-digit hexadecimal value.
*/
@objc public convenience init(hex4: UInt16) {
let divisor = CGFloat(15)
let red = CGFloat((hex4 & 0xF000) >> 12) / divisor
let green = CGFloat((hex4 & 0x0F00) >> 8) / divisor
let blue = CGFloat((hex4 & 0x00F0) >> 4) / divisor
let alpha = CGFloat( hex4 & 0x000F ) / divisor
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
/**
The six-digit hexadecimal representation of color of the form #RRGGBB.
- parameter hex6: Six-digit hexadecimal value.
*/
@objc public convenience init(hex6: UInt32, alpha: CGFloat = 1) {
let divisor = CGFloat(255)
let red = CGFloat((hex6 & 0xFF0000) >> 16) / divisor
let green = CGFloat((hex6 & 0x00FF00) >> 8) / divisor
let blue = CGFloat( hex6 & 0x0000FF ) / divisor
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
/**
The six-digit hexadecimal representation of color with alpha of the form #RRGGBBAA.
- parameter hex8: Eight-digit hexadecimal value.
*/
@objc public convenience init(hex8: UInt32) {
let divisor = CGFloat(255)
let red = CGFloat((hex8 & 0xFF000000) >> 24) / divisor
let green = CGFloat((hex8 & 0x00FF0000) >> 16) / divisor
let blue = CGFloat((hex8 & 0x0000FF00) >> 8) / divisor
let alpha = CGFloat( hex8 & 0x000000FF ) / divisor
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
/**
The rgba string representation of color with alpha of the form #RRGGBBAA/#RRGGBB, throws error.
- parameter rgba: String value.
*/
@objc public convenience init(rgba_throws rgba: String) throws {
guard rgba.hasPrefix("#") else {
throw UIColorInputError.missingHashMarkAsPrefix
}
let index = rgba.index(rgba.startIndex, offsetBy: 1)
let hexString = String(rgba[index...])
var hexValue: UInt32 = 0
guard Scanner(string: hexString).scanHexInt32(&hexValue) else {
throw UIColorInputError.unableToScanHexValue
}
switch (hexString.count) {
case 3:
self.init(hex3: UInt16(hexValue))
case 4:
self.init(hex4: UInt16(hexValue))
case 6:
self.init(hex6: hexValue)
case 8:
self.init(hex8: hexValue)
default:
throw UIColorInputError.mismatchedHexStringLength
}
}
/**
The rgba string representation of color with alpha of the form #RRGGBBAA/#RRGGBB, fails to default color.
- parameter rgba: String value.
*/
@objc public convenience init(_ rgba: String, defaultColor: UIColor = UIColor.clear) {
guard let color = try? UIColor(rgba_throws: rgba) else {
self.init(cgColor: defaultColor.cgColor)
return
}
self.init(cgColor: color.cgColor)
}
/**
Hex string of a UIColor instance.
- parameter includeAlpha: Whether the alpha should be included.
*/
@objc public func hexString(_ includeAlpha: Bool = true) -> String {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
self.getRed(&r, green: &g, blue: &b, alpha: &a)
if includeAlpha {
return String(format: "#%02X%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255), Int(a * 255))
} else {
return String(format: "#%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255))
}
}
}
# Acknowledgements
This application makes use of the following third party libraries:
## RSBarcodes_Swift
The MIT License (MIT)
Copyright (c) 2012-2014 P.D.Q.
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.
Generated by CocoaPods - https://cocoapods.org
......
......@@ -14,6 +14,36 @@
</dict>
<dict>
<key>FooterText</key>
<string>The MIT License (MIT)
Copyright (c) 2012-2014 P.D.Q.
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.
</string>
<key>License</key>
<string>MIT</string>
<key>Title</key>
<string>RSBarcodes_Swift</string>
<key>Type</key>
<string>PSGroupSpecifier</string>
</dict>
<dict>
<key>FooterText</key>
<string>Generated by CocoaPods - https://cocoapods.org</string>
<key>Title</key>
<string></string>
......
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO
FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/RSBarcodes_Swift"
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/RSBarcodes_Swift/RSBarcodes_Swift.framework/Headers"
LD_RUNPATH_SEARCH_PATHS = $(inherited) /usr/lib/swift '@executable_path/Frameworks' '@loader_path/Frameworks' '@executable_path/../../Frameworks'
LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift
OTHER_LDFLAGS = $(inherited) -framework "AVFoundation" -framework "CoreImage" -framework "QuartzCore" -framework "RSBarcodes_Swift"
OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS
PODS_BUILD_DIR = ${BUILD_DIR}
PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
PODS_PODFILE_DIR_PATH = ${SRCROOT}/.
......
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO
FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/RSBarcodes_Swift"
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/RSBarcodes_Swift/RSBarcodes_Swift.framework/Headers"
LD_RUNPATH_SEARCH_PATHS = $(inherited) /usr/lib/swift '@executable_path/Frameworks' '@loader_path/Frameworks' '@executable_path/../../Frameworks'
LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift
OTHER_LDFLAGS = $(inherited) -framework "AVFoundation" -framework "CoreImage" -framework "QuartzCore" -framework "RSBarcodes_Swift"
OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS
PODS_BUILD_DIR = ${BUILD_DIR}
PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
PODS_PODFILE_DIR_PATH = ${SRCROOT}/.
......
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>${PRODUCT_BUNDLE_IDENTIFIER}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>5.1.1</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>${CURRENT_PROJECT_VERSION}</string>
<key>NSPrincipalClass</key>
<string></string>
</dict>
</plist>
#import <Foundation/Foundation.h>
@interface PodsDummy_RSBarcodes_Swift : NSObject
@end
@implementation PodsDummy_RSBarcodes_Swift
@end
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
FOUNDATION_EXPORT double RSBarcodes_SwiftVersionNumber;
FOUNDATION_EXPORT const unsigned char RSBarcodes_SwiftVersionString[];
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO
CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/RSBarcodes_Swift
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift
OTHER_LDFLAGS = $(inherited) -framework "AVFoundation" -framework "CoreImage" -framework "QuartzCore"
OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS
PODS_BUILD_DIR = ${BUILD_DIR}
PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
PODS_ROOT = ${SRCROOT}
PODS_TARGET_SRCROOT = ${PODS_ROOT}/RSBarcodes_Swift
PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates
PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier}
SKIP_INSTALL = YES
USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES
framework module RSBarcodes_Swift {
umbrella header "RSBarcodes_Swift-umbrella.h"
export *
module * { export * }
}
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO
CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/RSBarcodes_Swift
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift
OTHER_LDFLAGS = $(inherited) -framework "AVFoundation" -framework "CoreImage" -framework "QuartzCore"
OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS
PODS_BUILD_DIR = ${BUILD_DIR}
PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
PODS_ROOT = ${SRCROOT}
PODS_TARGET_SRCROOT = ${PODS_ROOT}/RSBarcodes_Swift
PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates
PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier}
SKIP_INSTALL = YES
USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES
......@@ -7,7 +7,7 @@
<key>WarplySDKFrameworkIOS.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>1</integer>
<integer>2</integer>
</dict>
</dict>
</dict>
......