From 0a5150ef375d68157be991e4363b39c95355ecda Mon Sep 17 00:00:00 2001 From: R0CKSTAR Date: Wed, 28 Sep 2016 09:54:24 +0800 Subject: [PATCH] Add String extension to convert argb string to rgba string --- HEXColor/UIColorExtension.swift | 27 ++++++++++++++++++++++++++- HEXColorTests/HEXColorTests.swift | 10 ++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/HEXColor/UIColorExtension.swift b/HEXColor/UIColorExtension.swift index f674678..bf06bc6 100644 --- a/HEXColor/UIColorExtension.swift +++ b/HEXColor/UIColorExtension.swift @@ -91,7 +91,7 @@ extension UIColor { var hexValue: UInt32 = 0 guard Scanner(string: hexString).scanHexInt32(&hexValue) else { - throw UIColorInputError.unableToScanHexValue + throw UIColorInputError.unableToScanHexValue } switch (hexString.characters.count) { @@ -140,3 +140,28 @@ extension UIColor { } } } + +extension String { + /** + Convert argb string to rgba string. + */ + public func argb2rgba() -> String? { + guard self.hasPrefix("#") else { + return nil + } + + let hexString: String = self.substring(from: self.characters.index(self.startIndex, offsetBy: 1)) + switch (hexString.characters.count) { + case 4: + return "#" + + hexString.substring(from: self.characters.index(self.startIndex, offsetBy: 1)) + + hexString.substring(to: self.characters.index(self.startIndex, offsetBy: 1)) + case 8: + return "#" + + hexString.substring(from: self.characters.index(self.startIndex, offsetBy: 2)) + + hexString.substring(to: self.characters.index(self.startIndex, offsetBy: 2)) + default: + return nil + } + } +} diff --git a/HEXColorTests/HEXColorTests.swift b/HEXColorTests/HEXColorTests.swift index 897da59..843ec75 100644 --- a/HEXColorTests/HEXColorTests.swift +++ b/HEXColorTests/HEXColorTests.swift @@ -292,6 +292,16 @@ class HEXColorTests: XCTestCase { XCTAssertEqual("#AABBCC", hexColor.hexString(false)) XCTAssertEqual("#AABBCCDD", hexColor.hexString(true)) } + + // MARK: - Convert argb string to rgba string + + func testArgb2rgba() { + let rgba = "#2468".argb2rgba() + XCTAssertEqual("#4682", rgba) + + let rrggbbaa = "#22446688".argb2rgba() + XCTAssertEqual("#44668822", rrggbbaa) + } } extension UIColor {