这是一种创建视图的方法,该视图允许根据来自滑块(或任何东西)的输入来 360 度旋转其双色渐变。传入的滑块值(下面的“x”变量)介于 0.0 和 1.0 之间。
在 0.0 时,渐变是水平的(颜色 A 在上面,颜色 B 在下面),旋转 360 度到值 1.0(与值 0.0 相同 - 或完全旋转)。
例如当 x = 0.25 时,颜色 A 为左,颜色 B 为右。在 0.5 时,颜色 A 位于下方,颜色 B 位于上方,0.75 时颜色 A 位于右侧,颜色 B 位于左侧。它从右到左逆时针旋转。
它有四个参数:frame, colourA, colourB 和输入值 (0-1)。
-(UIView *)gradientViewWithFrame:(CGRect)frame colourA:(UIColor *)A colourB:(UIColor *)B rotation:(float)x {
//x is between 0 and 1, eg. from a slider, representing 0 - 360 degrees
//colour A starts on top, with colour B below
//rotations move anti-clockwise
//1. create the colour view
UIView * colourView = [UIView new];
colourView.frame = frame;
//2. create the gradient layer
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = colourView.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[A CGColor], (id)[B CGColor], nil];
[colourView.layer insertSublayer:gradient atIndex:0];
//3. create coordinates
float a = pow(sinf((2*M_PI*((x+0.75)/2))),2);
float b = pow(sinf((2*M_PI*((x+0.0)/2))),2);
float c = pow(sinf((2*M_PI*((x+0.25)/2))),2);
float d = pow(sinf((2*M_PI*((x+0.5)/2))),2);
//4. set the gradient direction
[gradient setStartPoint:CGPointMake(a, b)];
[gradient setEndPoint:CGPointMake(c, d)];
return colourView;
}