我一直在尝试使用CAGradientLayer来制作这个。
最初,我尝试使用.colors属性来设置渐变背景,但这只是一个背景填充。尝试此方法时,我尝试添加另一个具有黑色背景的CALayer,但我无法正确设置半径,并且它会在圆角处创建各种厚度的线条。
是否有更好的方法来创建带渐变的圆角矩形边框? CALayer不能实现这一点,我应该转移到UIBezierPath或CGContextRef吗?
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(12*twelthWidth - squareCentre.x - squareSize.width, squareCentre.y, squareSize.width, squareSize.height)];
// Create the rounded layer, and mask it using the rounded mask layer
CAGradientLayer *roundedLayer = [CAGradientLayer layer];
[roundedLayer setFrame:view.bounds];
roundedLayer.cornerRadius = view.bounds.size.width/5;
roundedLayer.masksToBounds = YES;
roundedLayer.colors = [NSArray arrayWithObjects:(id)[[UIColor redColor] CGColor], (id)[[UIColor blueColor] CGColor], nil];
roundedLayer.borderWidth = 4;
roundedLayer.borderColor = [UIColor clearColor].CGColor;
// Add these two layers as sublayers to the view
int BorderWidth = 5;
CALayer *solidColour = [CALayer layer];
solidColour.cornerRadius = view.bounds.size.width/5;
solidColour.masksToBounds = YES;
solidColour.backgroundColor = [UIColor blackColor].CGColor;
[solidColour setFrame:CGRectMake(BorderWidth, BorderWidth, roundedLayer.bounds.size.width - 2*BorderWidth, roundedLayer.bounds.size.height - 2*BorderWidth)];
[view.layer insertSublayer:roundedLayer atIndex:0];
[view.layer insertSublayer:solidColour above:roundedLayer];
[self.view addSubview:view];
生成的效果如下图所示:
其中角部不是直角。是否需要为第二层计算不同的半径?
编辑
将实色的半径设置为solidColour.bounds.size.width/5后,仍然不正确 - 角部太细了。
solidColour.bounds.size.width/5
? - Wain