diff --git a/Sources/Internal/RCBit.swift b/Sources/Internal/RCBit.swift index 2cab581..a3566bb 100644 --- a/Sources/Internal/RCBit.swift +++ b/Sources/Internal/RCBit.swift @@ -27,6 +27,10 @@ enum RCBit: Int { case zero case one + var boolValue: Bool { + return self == .zero ? false : true + } + init?(_ character: Character) { switch character { case "0": self = .zero diff --git a/Sources/Internal/RCConstants.swift b/Sources/Internal/RCConstants.swift new file mode 100644 index 0000000..39a52a6 --- /dev/null +++ b/Sources/Internal/RCConstants.swift @@ -0,0 +1,34 @@ +// MIT License + +// Copyright (c) 2020 Haik Aslanyan + +// 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. + +import CoreGraphics + +struct RCConstants { + static let maxBites = 400 + static let level1BitesCount = 33 + static let level2BitesCount = 33 + static let level3BitesCount = 34 + static let imageScale: CGFloat = 0.7 + static let dotSizeScale: CGFloat = 0.12 + static let dotPatterns: [CGFloat] = [6.5, 4.5, 2.5] + +} diff --git a/Sources/Internal/RCDrawer.swift b/Sources/Internal/RCDrawer.swift index 493d6bd..bdfa4a1 100644 --- a/Sources/Internal/RCDrawer.swift +++ b/Sources/Internal/RCDrawer.swift @@ -31,7 +31,7 @@ class RCDrawer { } func draw() -> UIImage { - let rect = CGRect(origin: .zero, size: CGSize(width: image.size, height: image.size)) + let rect = CGRect(origin: .zero, size: CGSize(width: image.size + image.contentInsets.left + image.contentInsets.right, height: image.size + image.contentInsets.top + image.contentInsets.bottom)) let renderer = UIGraphicsImageRenderer(bounds: rect, format: .default()) let image = renderer.image { context in let cgContext = context.cgContext @@ -40,7 +40,9 @@ class RCDrawer { context.fill(rect) } self.image.tintColor.setFill() - let size = self.image.size - self.image.size * 0.15 + self.image.tintColor.setStroke() + cgContext.translateBy(x: self.image.contentInsets.left, y: self.image.contentInsets.top) + let size = self.image.size - self.image.size * RCConstants.dotSizeScale let halfSize = size / 2 [(halfSize, 0), (size, halfSize), (halfSize, size), (0, halfSize)].map({CGPoint(x: $0.0, y: $0.1)}).forEach { point in cgContext.saveGState() @@ -49,15 +51,16 @@ class RCDrawer { cgContext.restoreGState() } cgContext.saveGState() - cgContext.translateBy(x: rect.size.height / 4, y: rect.size.height / 4) - cgContext.scaleBy(x: 0.5, y: 0.5) + let imageTranslation = rect.size.height * (1 - RCConstants.imageScale) / 2 + cgContext.translateBy(x: imageTranslation, y: imageTranslation) + cgContext.scaleBy(x: RCConstants.imageScale, y: RCConstants.imageScale) drawImage() cgContext.restoreGState() for value in self.image.bits.enumerated() { cgContext.saveGState() cgContext.translateBy(x: self.image.size / 2, y: self.image.size / 2) - cgContext.rotate(by: CGFloat(value.offset) * CGFloat.pi / 2) - drawMessage(row: value.element) + cgContext.rotate(by: CGFloat(value.offset - 1) * CGFloat.pi / 2) + drawMessage(group: value.element) cgContext.restoreGState() } } @@ -68,8 +71,8 @@ class RCDrawer { private extension RCDrawer { func drawDot() { let dot = UIBezierPath() - let patternSingleSize = image.size * 0.15 / 6.5 - let patternSizes = [6.5, 4.5, 2.5].map({$0 * patternSingleSize}) + let patternSingleSize = image.size * RCConstants.dotSizeScale / RCConstants.dotPatterns.max()! + let patternSizes = RCConstants.dotPatterns.map({$0 * patternSingleSize}) for value in patternSizes.enumerated() { let path = UIBezierPath(ovalIn: CGRect(x: (patternSizes[0] - value.element) / 2, y: (patternSizes[0] - value.element) / 2, width: value.element, height: value.element)) path.close() @@ -93,7 +96,33 @@ private extension RCDrawer { image.draw(in: scaledImageRect, blendMode: .normal, alpha: 1) } - func drawMessage() { - + func drawMessage(group: [[RCBit]]) { + let lineWidth = image.size * RCConstants.dotSizeScale / 7 //number of lines including spaces + let radius = (self.image.size - lineWidth) / 2 + let path = UIBezierPath() + let radiuses = Array(group.indices.map({radius - lineWidth * CGFloat($0 * 2)}).reversed()) + zip(radiuses, group).forEach { + let bits = $0.1 + let radius = $0.0 + let startPosition = asin(self.image.size * RCConstants.dotSizeScale / radius / 1.5) + let distancePerBit = (CGFloat.pi / 2 - startPosition - startPosition) / CGFloat(bits.count) + var drawFromIdx = -1 + bits.enumerated().forEach { value in + if drawFromIdx < 0 && value.element.boolValue { + drawFromIdx = value.offset + } + if (!value.element.boolValue || value.offset == bits.count - 1) && drawFromIdx >= 0 { + let startAngel = startPosition + CGFloat(drawFromIdx) * distancePerBit + let distance = value.element.boolValue ? (value.offset + 1) : value.offset + let endAngel = startAngel + CGFloat(distance - drawFromIdx) * distancePerBit + let linePath = UIBezierPath(arcCenter: .zero, radius: radius, startAngle: startAngel, endAngle: endAngel, clockwise: true) + path.append(linePath) + drawFromIdx = -1 + } + } + } + path.lineWidth = lineWidth + path.lineCapStyle = .round + path.stroke() } } diff --git a/Sources/Internal/Reed Solomon/RCMatrix.swift b/Sources/Internal/RCMatrix.swift similarity index 83% rename from Sources/Internal/Reed Solomon/RCMatrix.swift rename to Sources/Internal/RCMatrix.swift index 2c4962e..49578f7 100644 --- a/Sources/Internal/Reed Solomon/RCMatrix.swift +++ b/Sources/Internal/RCMatrix.swift @@ -67,45 +67,51 @@ extension RCMatrix { return matrix } - static func vandermonde(rows: Int, columns: Int) -> RCMatrix { - let matrix = RCMatrix(rows: rows, columns: columns) - return RCMatrix(rows: rows, columns: columns) - } - subscript(row: Int, column: Int) -> Float { get { - guard row <= self.rows, column <= self.columns else { - fatalError("out of bounds") + return data.withUnsafeBufferPointer { buffer in + return buffer[self.rows * row + column] } - return data[self.rows * row + column] } set { - data[self.rows * row + column] = newValue + data.withUnsafeMutableBufferPointer { buffer in + buffer[self.rows * row + column] = newValue + } } } func row(for index: Int) -> [Float] { - guard index <= self.rows else { - fatalError("out of bounds") + return data.withUnsafeBufferPointer { buffer in + let range = (columns * index)..<(columns * (index + 1)) + return Array(buffer[range]) } - let range = (columns * index)..<(columns * (index + 1)) - return Array(data[range]) } func column(for index: Int) -> [Float] { return stride(from: 0, to: data.count, by: self.columns).map { rowIndex in - data[index + rowIndex] + data.withUnsafeBufferPointer { buffer in + return buffer[index + rowIndex] + } } } func rowsData() -> [[Float]] { - return stride(from: 0, to: data.count, by: self.columns).map { index in - Array(data[index ..< min(index + self.columns, data.count)]) + return data.withUnsafeBufferPointer { buffer in + stride(from: 0, to: data.count, by: self.columns).map { index in + Array(buffer[index ..< min(index + self.columns, data.count)]) + } } } func columnsData() -> [[Float]] { - return (0.. UIImage { let bits = try encode(message: image.message) - image.bits = stride(from: 0, to: bits.count, by: bits.count / 4).map({Array(bits[$0 ..< min($0 + bits.count / 4, bits.count)])}) + let bitChunks = stride(from: 0, to: bits.count, by: bits.count / 4).map({Array(bits[$0 ..< min($0 + bits.count / 4, bits.count)])}) + image.bits = bitChunks.map { chunk -> [[RCBit]] in + return [0.. [RCBit] { guard validate(message) else { throw RCCoderError.inValidText } - var dataBytes = [Int](repeating: 0, count: configuration.maxMessageCount) - message.enumerated().forEach({dataBytes[$0.offset] = configuration.symbols.firstIndex(of: $0.element)! + 1}) - return dataBytes.map { byte -> [RCBit] in + let dataBytes = message.map({configuration.symbols.firstIndex(of: $0)! + 1}) + let encodedBits = dataBytes.map { byte -> [RCBit] in var stringValue = String(repeating: "0", count: configuration.bitesPerSymbol) stringValue += String(byte, radix: 2) return stringValue.suffix(configuration.bitesPerSymbol).compactMap({RCBit($0)}) }.flatMap({$0}) + var totalBits = [RCBit](repeating: .zero, count: RCConstants.maxBites) + totalBits.insert(contentsOf: encodedBits, at: 0) + return Array(totalBits.prefix(RCConstants.maxBites)) } private func decode(_ bits: [RCBit]) throws -> String { diff --git a/Sources/Public/RCCoderConfiguration.swift b/Sources/Public/RCCoderConfiguration.swift index 369bb3b..159af6b 100644 --- a/Sources/Public/RCCoderConfiguration.swift +++ b/Sources/Public/RCCoderConfiguration.swift @@ -22,7 +22,7 @@ import Foundation -public struct RCCoderConfiguration { +public class RCCoderConfiguration { public let symbols: [Character] public let maxMessageCount: Int @@ -31,39 +31,25 @@ public struct RCCoderConfiguration { CharacterSet(charactersIn: symbols.map({String($0)}).reduce("", +)) }() - public init(symbols: String, maxMessageCount: Int) throws { - var hash = [Character : Int]() - for value in symbols.enumerated() { - if hash[value.element] != nil { - throw RCCoderConfigurationError.containsDuplicateSymbols - } - hash[value.element] = value.offset - } + public init(symbols: String) { self.symbols = symbols.map({$0}) - self.maxMessageCount = maxMessageCount self.bitesPerSymbol = String(symbols.count, radix: 2).count + self.maxMessageCount = RCConstants.maxBites / bitesPerSymbol } public static var uuidConfiguration: RCCoderConfiguration { - return try! RCCoderConfiguration(symbols: "-abcdef0123456789", maxMessageCount: 36) + return RCCoderConfiguration(symbols: "-ABCDEF0123456789") } public static var numericConfiguration: RCCoderConfiguration { - return try! RCCoderConfiguration(symbols: ".,_0123456789", maxMessageCount: 25) + return RCCoderConfiguration(symbols: ".,_0123456789") } public static var defaultConfiguration: RCCoderConfiguration { - return try! RCCoderConfiguration(symbols: " -abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", maxMessageCount: 32) + return RCCoderConfiguration(symbols: " -abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") } public static var asciiConfiguration: RCCoderConfiguration { - return try! RCCoderConfiguration(symbols: ##"! "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"##, maxMessageCount: 42) - } -} - -public extension RCCoderConfiguration { - - enum RCCoderConfigurationError: Error { - case containsDuplicateSymbols + return RCCoderConfiguration(symbols: ##"! "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"##) } } diff --git a/Sources/Public/RCImage.swift b/Sources/Public/RCImage.swift index 81e802d..0611a24 100644 --- a/Sources/Public/RCImage.swift +++ b/Sources/Public/RCImage.swift @@ -29,7 +29,10 @@ public class RCImage { public var tintColor = UIColor.systemBlue public var attachmentImage: UIImage? public var isTransparent = false - internal var bits = [[RCBit]]() + public var contentInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) + internal var bits = [[[RCBit]]]() // 4 group of bits, each one with 3 lines of bit array - public init() {} + public init(message: String = "") { + self.message = message + } }