我已经尝试了一段时间,使用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之后,它仍然不对 - 它在角落处变得太薄 .
3 回答
您看到的问题是因为内角和外角半径相同 . 这就是导致线条厚度变化的原因 . 来自CSS-Tricks的这个插图突出了这个问题(即使您认为自己没有使用CSS,问题仍然是相同的):
解决方案是将内半径计算为:
如Joshua Hibbert所示:
如果您使用swift,只是为了您的方便
不使用视图边界来设置实体图层的
cornerRadius
,而是使用图层's frame value after you' ve将其设置为正确的插入值:有了这个,我得到以下图像