I've been using this macro in Objective-C:
我在Objective-C中使用了这个宏:
#define RGBA(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)]
I am trying to figure out how I can get the closest thing possible in swift. Any ideas?
我想弄清楚如何才能在swift中得到尽可能接近的东西。什么好主意吗?
3 个解决方案
#1
9
An extension on UIColor
is a valid option.
UIColor上的扩展是一个有效的选项。
extension UIColor {
convenience init(_ r: Double, _ g: Double, _ b: Double, _ a: Double) {
self.init(red: r/255, green: g/255, blue: b/255, alpha: a)
}
}
Usage
使用
let white = UIColor(255.0, 255.0, 255.0, 1.0)
#2
7
In the global scope provide:
在全球范围内规定:
func RGBA (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat) {
return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a)
}
and then use it with:
然后和:
var theColor : UIColor = RGBA (255, 255, 0, 1)
#3
0
What I did is to create a class method that returns the #define.
我所做的是创建一个返回#define的类方法。
Example:
例子:
.h file
. h文件
#define RGBA(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)]
+ (UIColor*)RGBA:(CGFloat)r g:(CGFloat)g b:(CGFloat)b a:(CGFloat)a;
.m file
m文件
+ (UIColor*)RGBA:(CGFloat)r g:(CGFloat)g b:(CGFloat)b a:(CGFloat)a { return RGBA(r, g, b, a); }
#1
9
An extension on UIColor
is a valid option.
UIColor上的扩展是一个有效的选项。
extension UIColor {
convenience init(_ r: Double, _ g: Double, _ b: Double, _ a: Double) {
self.init(red: r/255, green: g/255, blue: b/255, alpha: a)
}
}
Usage
使用
let white = UIColor(255.0, 255.0, 255.0, 1.0)
#2
7
In the global scope provide:
在全球范围内规定:
func RGBA (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat) {
return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a)
}
and then use it with:
然后和:
var theColor : UIColor = RGBA (255, 255, 0, 1)
#3
0
What I did is to create a class method that returns the #define.
我所做的是创建一个返回#define的类方法。
Example:
例子:
.h file
. h文件
#define RGBA(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)]
+ (UIColor*)RGBA:(CGFloat)r g:(CGFloat)g b:(CGFloat)b a:(CGFloat)a;
.m file
m文件
+ (UIColor*)RGBA:(CGFloat)r g:(CGFloat)g b:(CGFloat)b a:(CGFloat)a { return RGBA(r, g, b, a); }