问题描述
我正在尝试定义一种非常简单的实用程序方法,它将使我不必使用计算器将RGB值定义为百分比.当我查看Apple的示例代码"QuartzCache"时,在DrawView.m文件的第96行中,我看到了以下内容:
I'm attempting to define an extremely simple utility method that will save me from having to use a calculator to define RGB values as percentages. When I look into Apple's sample code called "QuartzCache", in the DrawView.m file, line 96, I see this:
float whiteColor[4] = {1, 1, 1, 1};
但是,当我尝试创建如下所示的方法时,编译器讨厌我.半小时的强化Google搜寻没有产生任何帮助.
However, when I attempt to created a method like the following, the compiler hates me. A half-hour of intensive Googling has not produced any help.
+(float[])percentagesRGBArray:(float[])rgbArray{
float red = rgbArray[0];
float green = rgbArray[1];
float blue = rgbArray[2];
float alpha = rgbArray[3];
red = red/255;
green = green/255;
blue = blue/255;
alpha = alpha;
float percentagesRGBArray[4] = {red, green, blue, alpha};
return percentagesRGBArray;
}
定义这种方法的正确方法是什么?我在这里做错了什么?
What is the proper way to define such a method? What am I doing wrong here?
推荐答案
定义包含所有组件的struct
,或将每个单独的组件包装在NSNumber
中.或者,使用NSColor
实例包含您的颜色分量.
Define a struct
that contains all of the components, or wrap up each individual component in an NSNumber
. Alternatively, use an NSColor
instance to contain your colour components.
-
struct
方式:
typedef struct
{
float red;
float green;
float blue;
float alpha;
} MyColor;
- (MyColor) percentagesRGBArray:(MyColor) incoming
{
MyColor result;
result.red = incoming.red / 255;
result.green = incoming.green / 255;
result.blue = incoming.blue / 255;
result.alpha = incoming.alpha;
return result;
}
NSNumber
方式:
- (NSArray *) percentagesRGBArray:(float[]) rgbArray
{
NSNumber *red = [NSNumber numberWithFloat:rgbArray[0] / 255];
NSNumber *green = [NSNumber numberWithFloat:rgbArray[1] / 255];
NSNumber *blue = [NSNumber numberWithFloat:rgbArray[2] / 255];
NSNumber *alpha = [NSNumber numberWithFloat:rgbArray[3]];
return [NSArray arrayWithObjects:red, green, blue, alpha, nil];
}
NSColor
方式:
- (NSColor *) percentagesRGBArray:(float[]) rgbArray
{
CGFloat red = rgbArray[0] / 255;
CGFloat green = rgbArray[1] / 255;
CGFloat blue = rgbArray[2] / 255;
CGFloat alpha = rgbArray[3];
return [NSColor colorWithDeviceRed:red
green:green
blue:blue
alpha:alpha];
}
这篇关于Objective-C方法参数问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!