Параметры диаграммы

Описание: создание линейной диаграммы, использующей заданный источник данных.

Файл «ViewController.h»

#import "DataSource.h"
#import <Charting/ChartTouchesDelegate.h>
#import <Charting/Chart.h>
#import <Charting/TrendLine.h>
@interface ViewController : UIViewController<ChartTouchesDelegate>{
    Chart *chart;
    float max;
    float min;
    NSMutableDictionary *m_numberFormat;
    int axisType;
    BOOL hideAxis;
    int chartType;
    NSArray *m_colors;
    DataSource *datasource;
    SolidColorBrush *solidBrush;
    TrendLine *line;
    LevelLineHolder *levelLine;
}
- (ChartLabel *)createDefaultLabel;
- (void) setChartSettings;
- (void) drawAllSeries;
@end

Файл «ViewController.m»

#import "ViewController.h"
#define ColorWithRGBA(_r, _g, _b, _a) \
[UIColor colorWithRed:(_r) / 255.0f green:(_g) / 255.0f blue:(_b) / 255.0f alpha:(_a) / 255.0f]
@implementation ViewController
- (void)dealloc
{
    [super dealloc];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    m_numberFormat = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
                       [NSNumber numberWithBool:NO], @"asInSource",
                       [NSNumber numberWithInt:2], @"decNumbers",
                       [NSNumber numberWithBool:YES], @"separator",
                       @"", @"prefix",
                       @"", @"suffix",
                       [NSNumber numberWithBool:NO], @"negativeRed",
                       nil] retain];
    m_colors = [[NSArray arrayWithObjects:
                 ColorWithRGBA(19, 88, 138, 255),
                 ColorWithRGBA(109, 167, 192, 255),
                 ColorWithRGBA(41, 171, 226, 255),
                 ColorWithRGBA(0, 169, 157, 255),
                 ColorWithRGBA(103, 124, 139, 255),
                 ColorWithRGBA(221, 241, 250, 255),
                 ColorWithRGBA(169, 221, 243, 255),
                 ColorWithRGBA(102, 203, 196, 255),
                 ColorWithRGBA(208, 222, 232, 255),
                 ColorWithRGBA(190, 160, 186, 255),
                 nil] retain];
    // Создаем диаграмму и задаем размеры
    chart = [[Chart alloc] initWithName:@"CHart≥"];
    chart.frame=CGRectMake(0, 0, 600, 550);
    chart.backgroundColor = [UIColor whiteColor];
    chart.plotArea.zoomEnabled = NO;
    chart.usingRightToLeft = NO;
    chart.minimalHitRadius = 4;
    // Создаем кисть для заливки элементов диаграммы
    SolidColorBrush *br = [SolidColorBrush new];
    br.color = [UIColor lightGrayColor];
    br.opacity = 0.1;
    // Задаем параметры легенды
    chart.legend.background = [br autorelease];
    chart.legend.borderRadius = 2;
    chart.legend.borderThickness = 0;
    chart.legend.borderColor = [UIColor blackColor];
    chart.legend.font = [UIFont fontWithName:@"Arial" size:12];
    chart.legend.legendOrientation = LegendOrientationBottom;
    chart.legend.textColor = [UIColor blackColor];
    chart.legend.contentRotation = LegendContentRotationNone;
    // Задаем параметры области диаграммы
    chart.chartArea.borderColor = [UIColor whiteColor];
    chart.chartArea.background = [SolidColorBrush solidColorBrushWithColor:[UIColor whiteColor]];
    // Создаем источник данных диаграммы
    datasource = [[DataSource alloc] init];
    [self setChartSettings];
    [self drawAllSeries];
    // Задаем для диаграммы источник данных
    [chart setDataSource:datasource];
    [chart setDelegate:self];
    // Задаем минимальные и максимальные значения источника данных
    [datasource prepare];
    // Отстраиваем диаграмму
    for (ChartSeries *series in chart.seriesList) {
        [series.points removeAllObjects];
        [series forceDataUpdate];
    }
    // Выполняем пользовательский пример
    [self executeExample];
    // Отображаем диаграмму
    [self.view addSubview:chart];
}
// Функция для выполнения примера
-(void) executeExample{
    
}
- (void)drawAllSeries
{
    [chart deleteAllSeries]; // Удаляем все ряды данных
    // Создаем линию тренда
    line = [[[TrendLine alloc] init] autorelease];
    line.dataIndex = [NSString stringWithFormat:@"%d", 2];
    [line setDataIndex:@"3"];
    line.color = [UIColor redColor];
    line.thickness = 3;
    line.dataSource = datasource;
    line.chartView = chart;
    line.autoName = NO;
    line.name = @"Линия тренда";
    line.legendVisible = YES;
    line.visible = NO;
    [line updateData];
    // Добавляем линию тренда на диаграмму
    [chart addTrendLine:line];
    
    // Добавляем ряды на диаграмму
    int seriesCount = datasource.countSeries;
    for (int i = 0; i < seriesCount; ++i)
    {
        UIColor *color = [m_colors objectAtIndex:i % [m_colors count]];
        axisType = ValueAxisAbsolute;
        hideAxis = NO;
        ColumnSeries *ser = [[ColumnSeries new] autorelease];
        ser.background = [SolidColorBrush solidColorBrushWithColor:color];
        ser.shadowOffset  = CGSizeMake(0, 0);
        ser.showShadow = NO;
        ser.dataIndex = i;
        ser.fillRatio = 0.7;
        ser.borderThickness = 2.0;
        ser.borderColor = [UIColor blackColor];
        [chart addSeries:ser];
    }
    [chart forceDataUpdate];
    // Создаем линию уровня
    levelLine = [[LevelLineHolder alloc] init];
    levelLine.chartView = chart;
    levelLine.thickness = 2;
    levelLine.value = 12;
    levelLine.name = @"Линия уровня";
    levelLine.color = [UIColor blueColor];
    levelLine.legendVisible = YES;
    levelLine.visible = YES;
    levelLine.labelVisible = YES;
    // Добавляем линию уровня на диаграмму
    [chart addLevelLine:levelLine];
    // Отстраиваем оси
    ((ValueAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisLineX]]).valueAxisType = axisType;
    ((ValueAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisLineY]]).valueAxisType = axisType;
    ((ValueAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisLineX]]).visible = !hideAxis;
    ((ValueAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisLineY]]).visible = !hideAxis;
    [chart.plotArea redrawChart];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)setChartSettings
{
    // Задаем параметры оси X
    ValueAxis *axisX = (ValueAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisLineX]];
    axisX.axisThickness = 1;
    axisX.majorTicks.thickness = 0;
    axisX.minorTicks.thickness = 0;
    axisX.axisLabelsVertical = NO;
    axisX.axisLabelsVisible = YES;
    // Задаем параметры оси Y
    ValueAxis *axisY = (ValueAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisLineY]];
    axisY.axisLabelsVisible = YES;
    axisY.axisThickness = 1;
    axisY.majorTicks.thickness = 1;
    axisY.majorTicks.size = 3;
    axisY.minorTicks.thickness = 0;
    axisY.showGrid = YES;
    axisY.gridThickness = 1;
    axisY.gridColor = ColorWithRGBA(200, 200, 200, 255);
    axisY.caption.visible = YES;
    axisY.caption.text = @"axisY";
    axisY.caption.font = [UIFont fontWithName:@"Arial" size:20.0];
    axisY.axisLabelsVertical = NO;
    // Задаем отступы для легенды и области диаграммы
    Thickness th = {10,0,0,20};
    chart.legend.margin = th;
    th.bottom = 0;
    th.left = th.right = th.top = 10;
    chart.chartArea.padding = th;
}
- (void)chartDataReady:(id)sender
{
    NSLog(@"Data was load");
}
@end

См. также:

Создание линий уровня и тренда на диаграмме