如何设置角度

时间:2017-07-27 08:33:27

标签: ios objective-c gradient

我想在我的按钮上设置渐变,我必须用两种颜色设置简单的线性渐变(没有角度),但我不知道如何在渐变上设置角度值

角度: - 61

下面的图像定义psd渐变叠加效果

enter image description here

提前致谢

3 个答案:

答案 0 :(得分:2)

尝试一下,也许会有所帮助

- (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;

}

答案 1 :(得分: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];

相应地调整位置值和帧大小。

答案 2 :(得分: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

其他解决方案可能是找到矩形与角度定义的线的交点。