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

Описание: диаграмма строится по параметрам, заданным в данных файлах.

Файл «ViewController.h»

#import "Charting/Chart.h"
#import "Brush.h"
#import "Charting/ColumnSeries.h"
#import "Charting/AreaSeries.h"
#import "DataSource.h"
#import "Charting/BarSeries.h"
#import "Charting/PieSeries.h"
#import "Charting/LineSeries.h"
#import "Charting/LinePoint.h"
#import "Charting/ChartTouchesDelegate.h"
#import "Charting/ChartLabel.h"
#import "Charting/BubbleSeries.h"
#import "ChartTypes.h"
#import "Charting/ChartAnimationScale.h"
#import "Charting/ChartAnimationFade.h"
#import "Charting/ChartAnimationMove.h"
#import "Charting/ChartAnimationRotate.h"
#import "Charting/ChartAnimationPieMove.h"
#import "Charting/ChartAnimationDelegate.h"
@interface ViewController : UIViewController<ChartAnimationDelegate,ChartTouchesDelegate>{
    Chart *chart;
    float max;
    float min;
    NSMutableDictionary *m_numberFormat;
    int axisType;
    BOOL hideAxis;
    int chartType;
    NSArray *m_colors;
    DataSource *datasource;
    SolidColorBrush *solidBrush;
}
- (ChartLabel *)createDefaultLabel;
- (void) setChartSettings;
- (void) drawAllSeries;
- (NSDictionary *) createDictForBrushWithBaseColor:(UIColor *) color;
@end

Файл «ViewController.m»

#import "ViewController.h"
#import "CustomView.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.caption.text = @"Диаграмма";
    chart.caption.textColor = [UIColor blackColor];
    chart.caption.maxTextLength = 100;
    chart.caption.blockAlignment = AlignmentCenter;
    SolidColorBrush *br = [SolidColorBrush new];
    br.color = [UIColor lightGrayColor];
    // Определяем параметры легенды
    chart.legend.background = [br autorelease];
    chart.legend.borderRadius = 2;
    chart.legend.borderThickness = 1;
    chart.legend.borderColor = [UIColor whiteColor];
    chart.legend.font = [UIFont fontWithName:@"Arial" size:12];
    chart.legend.legendOrientation = LegendOrientationTop;
    chart.legend.textColor = [UIColor blackColor];
    chart.chartArea.borderColor = [UIColor whiteColor];
    LinearGradientBrush *linGradBrush = [LinearGradientBrush new];
    linGradBrush.startPoint = CGPointMake(0, 0);
    linGradBrush.endPoint = CGPointMake(0, 1);
    GradientStop *st1 = [[GradientStop alloc] initWithColor:[UIColor whiteColor] offset:0.2];
    GradientStop *st2 = [[GradientStop alloc] initWithColor:[UIColor grayColor] offset:0.95];
    [linGradBrush.gradientStops addObject:st1];
    [linGradBrush.gradientStops addObject:st2];
    chart.chartArea.background = linGradBrush;
    chart.usingRightToLeft = NO;
    chart.minimalHitRadius = 4;
    // Создаем источник данных
    datasource = [[DataSource alloc] init];
    [self setChartSettings];
    solidBrush = [SolidColorBrush new];
    solidBrush.color = [UIColor blackColor];
    [self drawAllSeries];
    // Задаем ссылку на источник данных
    [chart setDataSource :datasource];
    [chart setDelegate:self];
    // Задаем для источника данных максимальное и минимальное значения границы по оси Y
    [datasource prepare];
    for (ChartSeries *series in chart.seriesList) {
        [series forceDataUpdate];
    }
    // Выполняем пользовательский пример
    [self executeExample];
    // Отображаем диаграмму
    [self.view addSubview:chart];
}
// Функция для выполнения примера
-(void) executeExample{
    
};
- (void)drawAllSeries
{
    [chart deleteAllSeries];
    NSMutableDictionary *dict1 = [NSMutableDictionary new];
    int seriesCount = datasource.countSeries;
    for (int i = 0; i < seriesCount; ++i)
    {
        UIColor *color = [m_colors objectAtIndex:i % [m_colors count]];
        axisType = ValueAxisAbsolute;
        hideAxis = NO;
        LineSeries *ser = [[LineSeries new] autorelease];
        ser.backgroundColor = color;
        ser.marker.borderThickness = 1;
        ser.marker.borderColor = [UIColor blackColor];
        ser.markerBackground = [SolidColorBrush solidColorBrushWithColor:color];
        ser.noDataColor = [UIColor blueColor];
        ser.showShadow = NO;
        ser.dataIndex = i;
        ser.markerSize = 10;
        ser.thickness = 2;
        ser.defaultLabel = [self createDefaultLabel];
        [chart addSeries:ser];
    }
    [chart forceDataUpdate];
    ((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;
    NSLog(@"%@",dict1);
    [dict1 release];
}
- (void )viewDidUnload
{
    [super viewDidUnload];
}
- (BOOL )shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void )chartTouchesTapInView:(UIView *)v withPoint:(CGPoint)point
{
    UIView *sender = [v hitTest:point withEvent:nil];
    if ([sender isKindOfClass:[ChartPoint class]])
    {
        ChartPoint *pt = (ChartPoint *)sender;
        if (pt.chartLabel)
        {
            pt.chartLabelVisible = !pt.chartLabelVisible;
            if (pt.chartLabelVisible)
            {
                [pt moveAboveAllByZOrder];
                ((LinePoint *)pt).markerSize *= 1.1;
                ((LinePoint *)pt).marker.borderThickness = 2;
            }
            else
            {
                [pt restoreZOrder];
                ((LinePoint *)pt).markerSize *= 1.1;
                ((LinePoint *)pt).marker.borderThickness = 1;
            }
        }
        [chart setNeedsLayout];
    }
}
- (void)setChartSettings
{
    ValueAxis *axisX = (ValueAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisLineX]];
    axisX.axisThickness = 1;  // Толщина оси X
    axisX.majorTicks.thickness = 0; // Толщина основных делений на оси Х
    axisX.minorTicks.thickness = 0; // Толщина дополнительных делений на оси Х
    ValueAxis *axisY = (ValueAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisLineY]];
    axisY.axisThickness = 1; // Толщина оси Y
    axisY.majorTicks.thickness = 1;
    axisY.majorTicks.size = 3; // Длина делений
    axisY.minorTicks.thickness = 0;
    axisY.showGrid = NO;
    TimeAxis *timeAxis = ((TimeAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisTypeTimeline]]);
    timeAxis.visible = NO;
    Thickness th = {10,0,0,20}; // Отступы
    chart.legend.margin = th; // Отступы для легенды
    th.bottom = 20;
    th.left = th.right = th.top = 10;
    chart.chartArea.padding = th; // Отступы для области диаграмм
}
- (ChartLabel *)createDefaultLabel
{
    ChartLabel *result = [[[ChartLabel alloc] initWithFrame:CGRectZero] autorelease]; // Создаем метку
    result.background = [[SolidColorBrush new] autorelease]; // Задаем цвет
    result.borderColor = [UIColor blackColor]; // Определяем цвет границы
    result.borderThickness = 1;
    result.borderRadius = 10;
    result.font = [UIFont fontWithName:@"Arial" size:18]; // Шрифт
    result.textAlignment = UITextAlignmentCenter;
    result.textColor = [UIColor blackColor];
    result.mask = [NSString stringWithFormat:@"%@#FVAL%@",
                   (NSString *)[m_numberFormat objectForKey:@"prefix"],
                   (NSString *)[m_numberFormat objectForKey:@"suffix"]];
    result.countOfDecimalNumbers = [((NSNumber *)[m_numberFormat objectForKey:@"decNumbers"]) intValue];
    result.displayNegativesInRed = [(NSNumber *)[m_numberFormat objectForKey:@"negativeRed"] boolValue];
    result.hasHorizontalNoteLine = result.hasVerticalNoteLine = result.hasFootNoteLine = NO;
    result.minWidth = 0;
    return result;
}
- (void)chartDataReady:(id)sender
{
    NSLog(@"Data was load");
}
- (void)chartTouchesSwipeInView:(UIView *)v withDirection:(UISwipeGestureRecognizerDirection)direction
{
    NSLog(@"Swipe");
}
- (void)timeAxis:(TimeAxis *)timeAxis setDoubleIndex:(double)idx
{
    NSLog(@"%f",idx);
}
- (void)timeAxis:(TimeAxis *)timeAxis setIndex:(int)idx
{
    NSLog(@"%d",idx);
}
@end

См. также:

Градиентная заливка диаграммы