gpt4 book ai didi

ios - 如何将 UIColor 转换为十六进制(网页颜色文本字符串)?

转载 作者:可可西里 更新时间:2023-11-01 03:25:44 25 4
gpt4 key购买 nike

有没有一种简单的方法可以将 UIColor 转换为十六进制值?
或者我们是否必须使用 CGColorGetComponents 获取 RGB 分量,然后从那里计算出来?

例如 CGColorGetComponents(color.CGColor)[0] * 256 ?

最佳答案

我还必须将 UIColor 转换为其十六进制组件。

正如 lewiguez 已经指出的,github 上有一个非常好的类别做所有这些事情。

但因为我想了解它是如何完成的,所以我自己制作了 RGB 颜色的简单实现。

+ (NSString*)colorToWeb:(UIColor*)color
{
NSString *webColor = nil;

// This method only works for RGB colors
if (color &&
CGColorGetNumberOfComponents(color.CGColor) == 4)
{
// Get the red, green and blue components
const CGFloat *components = CGColorGetComponents(color.CGColor);

// These components range from 0.0 till 1.0 and need to be converted to 0 till 255
CGFloat red, green, blue;
red = roundf(components[0] * 255.0);
green = roundf(components[1] * 255.0);
blue = roundf(components[2] * 255.0);

// Convert with %02x (use 02 to always get two chars)
webColor = [[NSString alloc]initWithFormat:@"%02x%02x%02x", (int)red, (int)green, (int)blue];
}

return webColor;
}

欢迎所有反馈!

关于ios - 如何将 UIColor 转换为十六进制(网页颜色文本字符串)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8689424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com