Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support 0x prefix and alpha value on the frontend #72

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions Sources/Core/DynamicColor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,35 @@

public extension DynamicColor {
// MARK: - Manipulating Hexa-decimal Values and Strings


/**
Creates a color from an hex string (e.g. "#3498db"). The RGBA string are also supported (e.g. "#ff3498db"). ff is alpha

support (0x3498db)

If the given hex string is invalid the initialiser will create a black color.

- parameter hexString: A hexa-decimal color string representation.
*/
convenience init(_ hexString: String, alphaInFront front: Bool = true) {
var hexString = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
if hexString.hasPrefix("0x"){
hexString = hexString.removingPrefixes(["0x"])
}

if hexString.hasPrefix("#"){
hexString = hexString.removingPrefixes(["#"])
}

if hexString.count > 7 && front {
let prefix = String(hexString.prefix(2)) // 获取最前面的两个字符
let middle = String(hexString.dropFirst(2)) // 获取中间的部分
hexString = middle + prefix // 重新组合字符串
}
self.init(hexString: hexString)
}


/**
Creates a color from an hex string (e.g. "#3498db"). The RGBA string are also supported (e.g. "#3498dbff").
Expand Down Expand Up @@ -224,3 +253,12 @@ public extension DynamicColor {
return self.contrastRatio(with: otherColor) > context.minimumContrastRatio
}
}

extension String{

public func removingPrefixes(_ prefixes: [String]) -> String {
let pattern = "^(\(prefixes.map{"\\Q"+$0+"\\E"}.joined(separator: "|")))\\s?"
guard let range = self.range(of: pattern, options: [.regularExpression, .caseInsensitive]) else { return self }
return String(self[range.upperBound...])
}
}