圖表開發經歷

背景

來公司第2周,開發一個圖表方面的公共控件。基本的樣子如下:

chart.png

基本思路

查了一下,舊的工程里已經有關于圖標的控件了,純代碼寫的控件,功能也很全,基本能用。這次想來點不一樣的實現方法。

  1. X坐標,Y坐標等用xib實現
  2. 具體的畫圖部分,仍然用代碼實現
  3. 代碼寫界面的view可以在xib中預覽

第3點,代碼界面在xib中預覽好像只能用Swift做,這里沒有做

技術儲備

貝塞爾曲線

+ (instancetype)bezierPath;
+ (instancetype)bezierPathWithRect:(CGRect)rect;
+ (instancetype)bezierPathWithOvalInRect:(CGRect)rect;

- (void)moveToPoint:(CGPoint)point;
- (void)addLineToPoint:(CGPoint)point;
- (void)closePath;

@property(nonatomic) CGFloat lineWidth;

- (void)fill;
- (void)stroke;

CALayer

+ (instancetype)layer;

@property CGRect bounds;
@property CGRect frame;
@property(getter=isHidden) BOOL hidden;

@property(nullable, readonly) CALayer *superlayer;
@property(nullable, copy) NSArray<CALayer *> *sublayers;

- (void)addSublayer:(CALayer *)layer;
- (void)removeFromSuperlayer;
- (void)insertSublayer:(CALayer *)layer atIndex:(unsigned)idx;
- (void)insertSublayer:(CALayer *)layer below:(nullable CALayer *)sibling;
- (void)insertSublayer:(CALayer *)layer above:(nullable CALayer *)sibling;
- (void)replaceSublayer:(CALayer *)layer with:(CALayer *)layer2;

@property(nullable, strong) CALayer *mask;
@property BOOL masksToBounds;

- (CGPoint)convertPoint:(CGPoint)p fromLayer:(nullable CALayer *)l;
- (CGPoint)convertPoint:(CGPoint)p toLayer:(nullable CALayer *)l;
- (CGRect)convertRect:(CGRect)r fromLayer:(nullable CALayer *)l;
- (CGRect)convertRect:(CGRect)r toLayer:(nullable CALayer *)l;

- (void)setNeedsDisplay;
- (void)setNeedsDisplayInRect:(CGRect)r;

@property(nullable) CGColorRef backgroundColor;
@property CGFloat cornerRadius;
@property CGFloat borderWidth;
@property(nullable) CGColorRef borderColor;

@property(nullable) CGColorRef shadowColor;
@property CGSize shadowOffset;
@property CGFloat shadowRadius;

CAShapeLayer

@property(nullable) CGPathRef path;
@property(nullable) CGColorRef fillColor;
@property(nullable) CGColorRef strokeColor;
@property CGFloat lineWidth;

CAGradientLayer

@property(nullable, copy) NSArray *colors;
@property CGPoint startPoint;
@property CGPoint endPoint;

這個是填充path圍起來的區域的漸變顏色的

CATextLayer

@property(nullable, copy) id string; // 可接受屬性字符串
@property(nullable) CFTypeRef font;
@property CGFloat fontSize;
@property(nullable) CGColorRef foregroundColor;
@property(getter=isWrapped) BOOL wrapped;
@property(copy) NSString *truncationMode;
@property(copy) NSString *alignmentMode;

注意事項

  • 變換約束之后,更新界面,取得正確的frame
- (void)adjustYAxisLabelConstraint {
    NSInteger const yAxisCellNumber = 5;
    CGFloat labelToLabelOffset = self.plotView.bounds.size.height / yAxisCellNumber;
    for (NSLayoutConstraint *item in self.yAxisLabelConstraintArray) {
        item.constant = labelToLabelOffset;
    }
    
    // 變換約束之后,重新布局
    [self layoutIfNeeded];
}

當時由于[self layoutIfNeeded]這句沒加,導致frame的數值沒更新,畫圖頁面異常。
在用frame之前,調用[self layoutIfNeeded]是一個好習慣

- (void)loadPAGridLayer {
    if (!self.loadGridLayer) {
        return;
    }
    if (nil == self.gridLayer) {
        // 這里要取frame,所以先更新一下autolayout,防止數據是舊的
        [self layoutIfNeeded];
        self.gridLayer = [[PAGridLayer alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        [self.layer addSublayer:self.gridLayer];
    }    
}
  • 由于layer還只能用frame,不能用autolayout,所以顯示和隱藏用重繪所有圖層,是否加載相應的圖層比較方便
  • CAGradientLayer對封閉的區域起作用。如果給的路徑不封閉,它自己會自動給閉。
- (CGPathRef)drawLineWithMin:(CGFloat)min max:(CGFloat)max datas:(NSArray *)datas {
    UIBezierPath *path = [UIBezierPath bezierPath];
    NSArray *xAxisArray = [self generateXAxisArrayWithCount:datas.count];
    NSArray *yAxisArray = [self generateYAxisArrayWithMin:min max:max datas:datas];
    
    for (NSInteger i = 0; i < xAxisArray.count; i++) {
        CGPoint point = CGPointMake([xAxisArray[i] floatValue], [yAxisArray[i] floatValue]);
        if (0 == i) {
            [path moveToPoint:point];
        } else {
            [path addLineToPoint:point];
        }
    }
    
    return path.CGPath;
}

這樣寫,就會是一個折線的區域填充,自動閉合,一個不規則的區域。

- (CGPathRef)drawLineWithMin:(CGFloat)min max:(CGFloat)max datas:(NSArray *)datas {
    UIBezierPath *path = [UIBezierPath bezierPath];
    NSArray *xAxisArray = [self generateXAxisArrayWithCount:datas.count];
    NSArray *yAxisArray = [self generateYAxisArrayWithMin:min max:max datas:datas];
    
    for (NSInteger i = 1; i < xAxisArray.count; i++) {
        CGPoint startPoint = CGPointMake([xAxisArray[i - 1] floatValue], [yAxisArray[i - 1] floatValue]);
        CGPoint endPoint = CGPointMake([xAxisArray[i] floatValue], [yAxisArray[i] floatValue]);
        [path moveToPoint:startPoint];
        [path addLineToPoint:endPoint];
        [path closePath];
    }
    
    return path.CGPath;
}

這樣寫,就出現一個漸變的折線了。看上去是折線,實際上上是一堆閉合直線的組合。不過這樣做有一個缺點,就是折線結合部不連續,很容易看出有一個缺口。原因就是這是N個閉合區域的組合,各組合之間有空隙,要補起來就會很困難。

- (CGPathRef)drawLineWithMin:(CGFloat)min max:(CGFloat)max datas:(NSArray *)datas {
    UIBezierPath *path = [UIBezierPath bezierPath];
    NSArray *xAxisArray = [self generateXAxisArrayWithCount:datas.count];
    NSArray *yAxisArray = [self generateYAxisArrayWithMin:min max:max datas:datas];
    
    // CAGradientLayer 是對一個區域做顏色漸變。所以折線從起點到終點又回到原點,表示閉合的區域
    // 往前畫折線
    for (NSInteger i = 0; i < xAxisArray.count; i++) {
        CGPoint point = CGPointMake([xAxisArray[i] floatValue], [yAxisArray[i] floatValue]);
        if (0 == i) {
            [path moveToPoint:point];
        } else {
            [path addLineToPoint:point];
        }
    }
    // 按原路返回
    for (NSInteger i = (xAxisArray.count - 2); i > 0; i--) {
        CGPoint point = CGPointMake([xAxisArray[i] floatValue], [yAxisArray[i] floatValue]);
        [path addLineToPoint:point];
    }
    // 形成封閉區域
    [path closePath];
    
    return path.CGPath;
}

這樣做,就成為一個閉合區域,折角處的缺口就不見了。

例子代碼

zhangxusong888/PAChartView-xib

這里用到了第三方庫Masonry,方便代碼加限制,用的時候,要先裝CocoaPods,執行以下pod install命令,從git下載這個庫的源代碼才能編譯通過。這也是CocoaPods的一個弱點,用Carthage就不會有這種問題,它是用framework的,不會整合庫的源代碼進工程。

zhangxusong888/PAChartView-code

代碼調用的圖表控件,功能一樣

參考文章

可視化開發,IB 的新時代
onevcat/ClockFaceView
CALayer詳解
CAShapeLayer和CAGradientLayer
使用CAShapeLayer與UIBezierPath畫出想要的圖形
UIBezierPath精講
CAGradientLayer的一些屬性解析

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容