Skip to content

Commit

Permalink
Add String extension to convert argb string to rgba string
Browse files Browse the repository at this point in the history
  • Loading branch information
yeahdongcn committed Sep 28, 2016
1 parent b0ebb75 commit 0a5150e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
27 changes: 26 additions & 1 deletion HEXColor/UIColorExtension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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
}
}
}
10 changes: 10 additions & 0 deletions HEXColorTests/HEXColorTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 0a5150e

Please sign in to comment.