1. 程式人生 > >封閉折線圖形的漸變色

封閉折線圖形的漸變色

PE else 虛線 arr sep sets num osi rul

技術分享圖片

希望實現這個效果,於是在簡書上問了一個作者,讓我 :先用正常的CAGradientLayer做出漸變色,然後利用CAlayer的mask屬性進行裁切

https://www.jianshu.com/p/8c45d8a1645d#comment-23013690

嗯嗯 確實可以 但是還有一個問題就是那條黑色的線不知道怎麽畫成虛線,而且畫成如上圖實線的話,轉折處還是那麽不好。

這是代碼:在 "

ZYWChart

" 這個Demo上的修改

- (void)drawLineLayer
{
    ///漸變色
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame 
= self.bounds; gradient.colors = [NSArray arrayWithObjects: (id)[UIColor colorWithRed:0 green:143/255.0 blue:234/255.0 alpha:1.0].CGColor, (id)[UIColor colorWithRed:0 green:173/255.0 blue:234/255.0 alpha:1.0].CGColor, (id)[UIColor whiteColor].CGColor, nil];
///畫分時線 UIBezierPath *path = [UIBezierPath drawLine:self.modelPostionArray]; ZYWLineModel *lastPoint = _modelPostionArray.lastObject; //連線的順序是順時針 連結成封閉圖形之後即可填充顏色 [path addLineToPoint:CGPointMake(lastPoint.xPosition,self.height - self.topMargin - self.timeLayerHeight)];//最右下角那個點 [path addLineToPoint:CGPointMake(self.leftMargin, self.height
- self.topMargin - self.timeLayerHeight)];//最左下角那個點 ZYWLineModel *firstPoint = _modelPostionArray.firstObject; [path addLineToPoint:CGPointMake(self.leftMargin , self.height - self.topMargin - self.timeLayerHeight + firstPoint.yPosition)]; //[[UIColor whiteColor] setFill];// 走勢線下面的填充顏色 //[path fill]; // 填充顏色 [path stroke]; // stroke 表示連線 [path closePath]; // 得到封閉圖形 self.lineChartLayer = [CAShapeLayer layer]; self.lineChartLayer.path = path.CGPath;//線加到layer上 self.lineChartLayer.strokeColor = self.lineColor.CGColor; self.lineChartLayer.fillColor = [[UIColor orangeColor] CGColor]; self.lineChartLayer.lineWidth = self.lineWidth; self.lineChartLayer.lineCap = kCALineCapRound; self.lineChartLayer.lineJoin = kCALineJoinRound; self.lineChartLayer.contentsScale = [UIScreen mainScreen].scale; //[self.layer addSublayer:self.lineChartLayer]; //self.lineChartLayer.fillRule = kCAFillRuleEvenOdd; gradient.mask = self.lineChartLayer; [self.layer addSublayer:gradient]; [self startRoundAnimation]; //再加一條蓋在上面的線? CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetLineWidth(context, 3); //不平滑 CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor); CGContextSetShouldAntialias(context, YES); [self.modelPostionArray enumerateObjectsUsingBlock:^(ZYWLineModel* obj, NSUInteger idx, BOOL * _Nonnull stop) { if (idx == 0) { CGContextMoveToPoint(context, obj.xPosition, obj.yPosition); } else { CGContextAddLineToPoint(context, obj.xPosition, obj.yPosition); } }]; CGContextStrokePath(context); }

後來發現gitHub上 "Charts"這個庫其實就實現了這種漸變色

技術分享圖片

然後又學習了一下 這個庫的引入和基本使用

引入:https://www.tuicool.com/articles/JFBFBjj

用法:https://blog.csdn.net/wis8520/article/details/70157451

封閉折線圖形的漸變色