CGRect rect = CGRectMake(100, 100, 100, 100);
UIView * bgView = [[UIView alloc]initWithFrame:rect];
bgView.backgroundColor = [UIColor grayColor];
[self.view addSubview:bgView];
CAShapeLayer * trackLayer = [CAShapeLayer layer];
trackLayer.frame = bgView.bounds;
[bgView.layer addSublayer:trackLayer];
trackLayer.fillColor = [[UIColor blackColor] CGColor];//填充颜色,这里应该是 clearColor
trackLayer.strokeColor = [[UIColor redColor] CGColor];//边框颜色
trackLayer.opacity = 0.5;
trackLayer.lineCap = kCALineCapRound;
trackLayer.lineWidth = 4.0; // 红色的边框宽度
UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(50, 50) radius:48 startAngle:degreesToRadians(-210) endAngle:degreesToRadians(30) clockwise:YES];
//角度是从 -210到30度,具体可以看如下图所示
trackLayer.path = [path CGPath];
运行后的结果如下
基于以上的代码,下面添加渐变的效果
CALayer * gradinetLayer = [CALayer layer];
CAGradientLayer * gradLayer1 = [CAGradientLayer layer];
gradLayer1.frame = CGRectMake(0, 0, bgView.frame.size.width/2, bgView.frame.size.height);
[gradLayer1 setColors:[NSArray arrayWithObjects:(id)[[UIColor redColor] CGColor],(id)[UIColorFromRGB(0xfde802) CGColor], nil]];
[gradLayer1 setLocations:@[@0.5,@0.9,@1 ]];
[gradLayer1 setStartPoint:CGPointMake(0.5, 1)];
[gradLayer1 setEndPoint:CGPointMake(0.5, 0)];
[gradinetLayer addSublayer:gradLayer1];
CAGradientLayer * gradLayer2 = [CAGradientLayer layer];
gradLayer2.frame = CGRectMake(bgView.frame.size.width/2, 0, bgView.frame.size.width/2, bgView.frame.size.height);
[gradLayer2 setColors:[NSArray arrayWithObjects:(id)[UIColorFromRGB(0xfde802) CGColor],(id)[[UIColor blueColor] CGColor], nil]];
[gradLayer2 setStartPoint:CGPointMake(0.5, 0)];
[gradLayer2 setEndPoint:CGPointMake(0.5, 1)];
[gradinetLayer addSublayer:gradLayer2];
//[gradinetLayer setMask:trackLayer];
[bgView.layer addSublayer:gradinetLayer];
本文转自 张江论坛 转载请注明 http://www.999dh.net/home.php?mod=space&uid=1&do=blog&quickforward=1&id=328
以上的代码运行后得到的结果如下:
解释如下:
setLocations 理论上来说,是设置 colors的显示区域的(这里还未弄清楚原理)
setStartPoint 是颜色的开始渐变的开始点,默认的是(0,0)也就是左上角
setEndPoint 是颜色的停止渐变的点,默认的是(1,1)
如果按默认的来,gradLayer1 的颜色渐变应该是从左上角由redcolor渐变到右下角(颜色为 0xfde802)
而代码中设置的 startPoint为(0.5,1),指的是在x轴中间,y轴底部;endPoint为(0.5,0)指的是在x轴中间,y轴顶部。
最后将代码[gradinetLayer setMask:trackLayer]; 注释去掉,得到如下的运行结果
这里主要的作用就是 setMask的功劳,但是为什么trackLayer的strokeColor没有生效,这里也不是很清楚。(哎,不懂的太多了哎)