本文来自简书,原文地址:http://www.jianshu.com/p/f7906f5b4f4c
最近一段时间写了一个iOS的K线图。写这个纯属个人兴趣,正好提高一下自己绘图方面的能力。在写的时候,参考了Cocoa-Charts 的实现思路。 废话不多说,先上图:
特点:
采用 CAShapeLayer + UIBezierPath绘制,绘制效率高,占用内存低底层视图是UIScrollView,ScrollView上面添加一个View,所有的绘制在这个View上完成。体验流畅丝滑,FPS平均在55帧以上指标支持MACD WR KDJ,指标计算采用TALib,方便扩展横竖屏切换
右拉加载更多数据
代理方法
- (
void)
displayScreenleftPostion:(CGFloat)leftPostion
startIndex:(NSInteger)index
count:(NSInteger)count;
- (
void)
longPressCandleViewWithIndex:(NSInteger)kLineModeIndex
kLineModel:(ZYWCandleModel *)kLineModel;
- (
void)
displayLastModel:(ZYWCandleModel *)kLineModel;
- (
void)displayMoreData;`
基础属性方法
@property (
nonatomic,
strong)
NSMutableArray<__kindof ZYWCandleModel*> *dataArray;
@property (
nonatomic,
strong)
NSMutableArray *currentDisplayArray;
@property (
nonatomic,
strong)
NSMutableArray *currentPostionArray;
@property (
nonatomic,
assign)
NSInteger displayCount;
@property (
nonatomic,
assign)
CGFloat candleSpace;
@property (
nonatomic,
assign)
CGFloat candleWidth;
@property (
nonatomic,
assign)
CGFloat minHeight;
@property (
nonatomic,
assign)
CGFloat leftPostion;
@property (
nonatomic,
assign)
NSInteger currentStartIndex;
@property (
nonatomic,
assign)
CGFloat previousOffsetX;
@property (
nonatomic,
assign)
CGFloat contentOffset;
@property (
nonatomic,
assign)
BOOL kvoEnable;
- (
CGPoint)getLongPressModelPostionWithXPostion:(
CGFloat)xPostion;
- (
void)stockFill;
- (
void)calcuteCandleWidth;
- (
void)updateWidth;
- (
void)drawKLine;
绘图基本思路
所有的绘制在UIView上面,UIView底层是一个ScrollView设置K线之间的间距与可视区域想要显示的K线个数,动态计算出K线的宽度。之所以没有直接设置K线宽度,是为了保证每次滑动的时候,屏幕内总是占满整数倍的K线个数。通过k线的个数,计算出当前View的与它的父视图ScrollView的宽度KVO监听ScrollView的contentOffset属性,计算每次滑动将要显示的K线数组(currentDisplayArray)计算currentDisplayArray的最大值与最小值,然后得出每一根K线对应屏幕的坐标,绘图
链接
[ZYWStock]https://github.com/zyw113/ZYWStock.git
在使用过程中如果遇到什么问题,欢迎给我简书留言,或者直接Pull request,欢迎star or fork。更多功能,敬请期待~~~