2017-07-27 37 views
0

我想設置梯度我的按鈕,我需要設置簡單線性漸變(無角)兩種顏色,但我不知道如何設置梯度如何設置漸變顏色與角度

角度值

角度: - 61

下面圖像定義PSD梯度疊加效果

enter image description here

預先感謝

+0

看看'startPoint'和'CAGradientLayer'的'endPoint'來設置一個角度(它設置「行」,但可以從一個角度來翻譯)。 – Larme

+0

如何根據角度值計算起始點和終點,因爲在特徵中角度值將被更改。如果你知道任何公式來計算起點和終點的角度值比請讓我知道@Larme –

+0

這是簡單的數學。沒有真正的編程 – Larme

回答

0
CAGradientLayer *gradientMask = [CAGradientLayer layer]; 
gradientMask.frame = CGRectMake(0, 0, myView.bounds.size.width, myView.bounds.size.height); 

gradientMask.colors = @[(id)[UIColor redColor].CGColor, 
         (id)[UIColor greenColor].CGColor]; 
gradientMask.locations = @[@0.0, @0.10, @0.60, @1.0]; 

[myView.layer insertSublayer:gradientMask atIndex:0]; 

相應地調整位置值和幀大小。

+0

我知道,但我如何計算基於角度值的起點和終點。如果你有任何這方面的公式比請讓我知道@kaushal –

0

這是通過PaintCode產生的稍微修改的碼,解決了只是此問題:

UIBezierPath* rectanglePath = [UIBezierPath bezierPathWithRect: self.view.bounds]; 
UIBezierPath* rectangleRotatedPath = [rectanglePath copy]; 
CGAffineTransform transform = CGAffineTransformMakeRotation(yourAngleInRadians); 
[rectangleRotatedPath applyTransform: transform]; 
CGRect rectangleBounds = CGPathGetPathBoundingBox(rectangleRotatedPath.CGPath); 
transform = CGAffineTransformInvert(transform); 

CGPoint startPoint = CGPointApplyAffineTransform(CGPointMake(CGRectGetMinX(rectangleBounds), CGRectGetMidY(rectangleBounds)), transform); 
CGPoint endPoint = CGPointApplyAffineTransform(CGPointMake(CGRectGetMaxX(rectangleBounds), CGRectGetMidY(rectangleBounds)), transform); 

代碼獲取您的初始矩形(黑色矩形)和角度(示爲黑線),旋轉矩形(你會得到藍色矩形),然後找到旋轉的矩形(紅色矩形)的邊界框。使用反轉變換(藍點)將邊界上的端點(紅點)轉換並轉換(旋轉)。

Finding endpoints

其他溶液可能被找到你的矩形的交點和由所述角度限定的線。

+0

感謝您的回答,但這種解決方案不適合我@mato –

1

試試吧,也許它會幫助

- (CAGradientLayer *)gradientLayerWithColors:(NSArray的*)顏色角度:(CGFloat的)角度{

CAGradientLayer *layer = [CAGradientLayer layer]; 
layer.colors = colors; 

CGFloat x = angle/360.f; 

CGFloat a = pow(sin((2*M_PI*((x+0.75)/2))),2); 
CGFloat b = pow(sin((2*M_PI*((x+0.0)/2))),2); 
CGFloat c = pow(sin((2*M_PI*((x+0.25)/2))),2); 
CGFloat d = pow(sin((2*M_PI*((x+0.5)/2))),2); 

layer.startPoint = CGPointMake(a, b); 
layer.endPoint = CGPointMake(c, d); 
return layer; 

}

+0

我已經嘗試過這種解決方案,但沒有設置適當的漸變@Eugene Sokolenko –