Ask Your Question
3

What is the method for changing the String color "rgba(255, 255, 255, 1)" to a Swift color?

asked 2021-08-31 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-09-12 09:00:00 +0000

david gravatar image

The method for changing the String color "rgba(255, 255, 255, 1)" to a Swift color is:

  1. Remove the "rgba" and parentheses from the string, leaving only the numbers and commas.
  2. Split the remaining string by commas to separate the Red, Green, Blue, and Alpha values into an array.
  3. Convert each value in the array from a string to a CGFloat.
  4. Create a new UIColor object using the converted values.

Here's the Swift code to accomplish this:

let colorString = "rgba(255, 255, 255, 1)"
let componentsString = colorString.replacingOccurrences(of: "rgba(", with: "").replacingOccurrences(of: ")", with: "")
let componentsArray = componentsString.components(separatedBy: ",").map { CGFloat(Float($0.trimmingCharacters(in: .whitespacesAndNewlines))!/255.0) }
let color = UIColor(red: componentsArray[0], green: componentsArray[1], blue: componentsArray[2], alpha: componentsArray[3])

The resulting color object will be a Swift UIColor with the same RGBA values as the original string.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-08-31 11:00:00 +0000

Seen: 10 times

Last updated: Sep 12 '22