我想创建一个自定义图表。
这将显示在 Y 轴上的数学数,例如 4
Y 轴图例将是开始日期和结束日期。
在 X 轴上,折线图将绘制每个匹配状态的点,例如
赢,平,输。
如何在目标 C 中做到这一点!?
我想创建一个自定义图表。
这将显示在 Y 轴上的数学数,例如 4
Y 轴图例将是开始日期和结束日期。
在 X 轴上,折线图将绘制每个匹配状态的点,例如
赢,平,输。
如何在目标 C 中做到这一点!?
要创建折线图,我们只需要一个 UIBezier 路径和一个 CAShapeLayer,将基于您拥有的数据的坐标点传递给将创建折线图的 UiBezierpath,然后将该路径添加到图层。
这是创建折线图的代码,
//Bezier path for ploting graph
_graphPath = [[UIBezierPath alloc]init];
[_graphPath setLineWidth:10];
//CAShapeLayer for graph allocation
_graphLayout = [CAShapeLayer layer];
_graphLayout.frame = CGRectMake(self.frame.size.width*0, 0, self.frame.size.width*0.8, (self.frame.size.height*0.9));
_graphLayout.fillColor = [[UIColor colorWithRed:0 green:0 blue:255 alpha:0.1] CGColor];
_graphLayout.strokeColor = [UIColor blueColor].CGColor;
_graphLayout.lineWidth = 2;
_graphLayout.path = [_graphPath CGPath];
_graphLayout.lineCap = @"round";
_graphLayout.lineJoin = @"round";
[self.layer addSublayer:_graphLayout];
将线添加到点并移动到点的代码
[_graphPath moveToPoint:CGPointMake(coord.x, coord.y)];
[_graphPath addLineToPoint:CGPointMake(coord.x, coord.y)];
_graphLayout.path = [_graphPath CGPath];
我已经制作了一种返回带有绘制数据点的视图的方法:
-(UIView *)createGraphWithFrameSize:(CGSize)frameSize
lineColor:(UIColor *)lineColor
xAxisMin:(float)xAxisMin
xAxisMax:(float)xAxisMax
yAxisMin:(float)yAxisMin
yAxisMax:(float)yAxisMax
dataPoints:(NSArray <NSValue *> *)dataPoints {
UIView *graph = [UIView new];
graph.backgroundColor = [UIColor clearColor];
graph.frame = CGRectMake(0, 0, frameSize.width, frameSize.height);
//
CAShapeLayer *line = [CAShapeLayer layer];
UIBezierPath *linePath = [UIBezierPath bezierPath];
int i = 0;
while (i < dataPoints.count) {
CGPoint point = [dataPoints[i] CGPointValue];
float xRatio = 1.0-((xAxisMax-point.x)/(xAxisMax-xAxisMin));
float yRatio = 1.0-((yAxisMax-point.y)/(yAxisMax-yAxisMin));
float x = xRatio*frameSize.width;
float y = (1.0-yRatio)*frameSize.height;
if (i == 0) {
[linePath moveToPoint:CGPointMake(x, y)];
} else {
[linePath addLineToPoint:CGPointMake(x, y)];
}
i++;
}
line.lineWidth = 2.0;
line.path = linePath.CGPath;
line.fillColor = [[UIColor clearColor] CGColor];
line.strokeColor = [lineColor CGColor];
[graph.layer addSublayer:line];
//
graph.clipsToBounds = YES;
return graph;
}
示例用法:
#define xy(__x,__y) [NSValue valueWithCGPoint:CGPointMake(__x,__y)]
UIView *plotView = [self createGraphWithFrameSize:CGSizeMake(300, 300)
lineColor:[UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:0.8]
xAxisMin:-5
xAxisMax:5
yAxisMin:-5
yAxisMax:5
dataPoints:@[xy(-5,-4),
xy(0,3),
xy(5,-4)]];
plotView.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.5];
[self.view addSubview:plotView];