Last active
July 29, 2021 20:30
-
-
Save sxua/7cbd8591cb74237af64ae627a502d695 to your computer and use it in GitHub Desktop.
Export colors from Xcode into CSV
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "csv" | |
require "json" | |
XCASSETS_NAME = "Colors.xcassets" | |
CSV.open(XCASSETS_NAME + ".csv", "wb") do |csv| | |
csv << ["Name", "Appearance", "HEX Value", "Alpha"] | |
Dir.glob(XCASSETS_NAME + "/**/*.colorset/Contents.json") do |file_name| | |
file = File.read(file_name) | |
json = JSON.parse(file) | |
if colors = json["colors"] | |
colors.each do |color| | |
color_space = color["color"]["color-space"] | |
appearance = color["appearances"] ? color["appearances"].first["value"] : "any" | |
case color_space | |
when "srgb" | |
components = color["color"]["components"] | |
red = components["red"] | |
green = components["green"] | |
blue = components["blue"] | |
alpha = components["alpha"] | |
hex_color = "" | |
[red, green, blue].each do |component| | |
if component.start_with?("0x") | |
hex_color += component[2..4] | |
else | |
hex_color += sprintf("%02X", (component.to_f * 255).to_i) | |
end | |
end | |
color_name = file_name.gsub(XCASSETS_NAME + "/", "").gsub(".colorset/Contents.json", "") | |
alpha_percentage = (alpha.to_f * 100).to_i.to_s + "%" | |
csv << [color_name, appearance, hex_color, alpha_percentage] | |
else | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment