【问题标题】:IOS Example of initWithCGColorIOS 示例 initWithCGColor
【发布时间】:2015-12-08 13:02:48
【问题描述】:

我放弃了,这太长了,我无法在任何地方找到答案。

UIColorFramework Reference 中有一个函数 initWithCGColor。你怎么用这个?有人可以帮忙举个例子吗?我希望将颜色初始化为特定值!

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIColor_Class/index.html#//apple_ref/occ/instm/UIColor/initWithCGColor:

【问题讨论】:

  • 你说的到一个特定的值是什么意思?
  • 具体值是什么?你已经有CGColorRef了吗?您能否详细说明您实际尝试做的事情,而不是您认为应该如何做的事情?
  • initWithCGColor:用于将颜色从 Core Graphics CGColorRef 转换为 UIColor。抱歉,但是从您的问题来看,您完全不清楚您要询问什么信息以及您想要达到什么目的。
  • 大家好。我为我的平庸问题道歉。据我估计,其他人会定期遇到相同的思考过程,因此我将其发布在这里供他们使用。
  • 澄清声明:UIColor.customColor(r,g,b)怎么办?

标签: ios uikit uicolor


【解决方案1】:

CGColorRef 是一个用于使用 Core 图形进行绘图的类。如果您想用特定的 RGB 值初始化 UIColorobject,请使用 - initWithRed:green:blue:alpha:

斯威夫特

let color = UIColor(red: 59/255.0, green: 136/255.0, blue: 195/255.0, alpha: 1)

Objective-C

 UIColor * color = [UIColor colorWithRed:59/255.0f green:136/255.0f blue:195/255.0f alpha:1];

出于帮助目的,我为 UIColor 添加了一些有用的扩展/宏,以便初始化对象而无需考虑除以 255。 我不是此代码的创建者,而是希望分享一些节省时间的代码的感激用户:

斯威夫特

public extension UIColor{

    class func initRGBA(r r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat) -> UIColor
    {
        return UIColor(red:r/255, green: g/255, blue: b/255, alpha: a)
    }

    class func initRGB(r r:CGFloat, g:CGFloat, b:CGFloat) -> UIColor
    {
        return UIColor.initRGBA(r:r, g:g, b:b, a:1)
    }

    class func initRGBGRAY(gray:CGFloat) -> UIColor
    {
        return UIColor.initRGBA(r:gray, g:gray, b:gray, a:1)
    }
    convenience init(rgb: UInt) {
        self.init(
            red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgb & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
    }  
}

/// Let's initialize a color
let color = UIColor.initRGB(r: 24, g: 80, b: 145)

Objective-C

#define RGBCOLOR(r,g,b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1]
#define RGBACOLOR(r,g,b,a) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:(a)]
#define RGBGRAYCOLOR(g) [UIColor colorWithRed:(g)/255.0f green:(g)/255.0f blue:(g)/255.0f alpha:1]

/// Let's initialize a color
UIColor * color = RGBCOLOR(87, 99, 132);

【讨论】:

  • 不客气。您使用的是 Swift 还是 ObjC ?我有一些用于初始化 UIColors 对象的宏。
  • 我希望你能意识到这样的答案能帮助很多人。您在这里为我们节省的累计时间,谢谢
猜你喜欢
  • 2017-12-07
  • 2012-01-10
  • 1970-01-01
  • 1970-01-01
  • 2012-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多