如何将CAGradientLayer旋转180度?

dar*_*han 5 iphone core-animation objective-c ios

CAGradientLayer为我的自定义创建了一个UIButton.创建它的代码如下:

CAGradientLayer *gradient = [CAGradientLayer layer];

gradient.frame = btn.bounds;
gradient.cornerRadius = 10.0f;
locations=[[NSArray alloc] initWithObjects: LOC_0, LOC_5, LOC_51,LOC_1, nil]; 
[gradient setLocations:locations];
colorNext=[[NSArray alloc] initWithObjects:(id) G3_rgb1, (id) G3_rgb2, (id) G3_rgb3, (id) G3_rgb4, nil]; 
gradient.colors = colorNext;

[btn.layer insertSublayer:gradient atIndex:0];
Run Code Online (Sandbox Code Playgroud)

我的问题是:按下按钮我需要将按钮的渐变视图改变180度,我该怎么做?

mac*_*erv 18

您还可以更改渐变的起点和终点.默认的startPoint是{0.5, 0.0}.默认的endPoint是{0.5, 1.0}.翻转那些使你的渐变走向另一个方向.

[gradient setStartPoint:CGPointMake(0.5, 1.0)];
[gradient setEndPoint:CGPointMake(0.5, 0.0)];
Run Code Online (Sandbox Code Playgroud)

将它们翻转以正常显示.


Bra*_*son 2

只要您维护指向渐变层的指针,您就应该能够通过提供一组反转的位置来反转渐变颜色顺序:

NSArray *newLocations = [[NSArray alloc] initWithObjects: [NSNumber numberWithFloat:(1.0 - [LOC_0 floatValue])], [NSNumber numberWithFloat:(1.0 - [LOC_5 floatValue])], [NSNumber numberWithFloat:(1.0 - [LOC_51 floatValue])], [NSNumber numberWithFloat:(1.0 - [LOC_1 floatValue])], nil]; 
[gradient setLocations:newLocations];
[newLocations release];

[gradient setNeedsDisplay];
Run Code Online (Sandbox Code Playgroud)

(如果您有 LOC_0 等的浮点值,这会更清晰)

我不确定是否-setNeedsDisplay需要,但它通常用于图层中的内容更改。

也就是说,Vanya 应用旋转变换的解决方案可能是实现此效果的最快方法。

作为评论,希望您的代码后面的某个地方有 a[locations release][colorNext release],否则您将泄漏位置和颜色数组。