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

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

Файл «ViewController.h»

#import <UIKit/UIKit.h>
#import <Charting/Chart.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 "RadialGradientBrush.h"
#import "GradientStop.h"
#import "Charting/ChartMarker+Charting.h"
@interface ViewController : UIViewController<ChartTouchesDelegate,TimeAxisDelegate>{
    Chart *chart;
    float max;
    float min;
    NSMutableDictionary *m_numberFormat;
    int axisType;
    BOOL hideAxis;
    int chartType;
    NSArray *m_colors;
    DataSource *datasource;
    RadialGradientBrush *radialBrush;
    BOOL outputInfo;
}
- (ChartLabel *)createDefaultLabel;
- (void) setChartSettings;
- (void) drawAllSeries;
- (NSDictionary *) createDictForBrushWithBaseColor:(UIColor *) color;
@end

Файл «ViewController.m»

#import "ViewController.h"
#import "Brush.h"
#import "UIColor+transition.h"
#import <charting/gradientbrush+charting.h>
#import <charting/gradientstop+charting.h>
#import <charting/lineargradientbrush+charting.h>
#import <charting/radialgradientbrush+charting.h>
#import <charting/solidcolorbrush+charting.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.plotArea.zoomEnabled = NO;
    // Определяем параметры заголовка
    chart.caption.text = @"Диаграмма";
    chart.caption.textColor = [UIColor blackColor];
    chart.caption.maxTextLength = 100;
    chart.caption.blockAlignment = AlignmentCenter;
    // Определяем параметры легенды
    chart.legend.background = [SolidColorBrush solidColorBrushWithColor:[UIColor whiteColor]];
    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];
    for (ChartSeries *s in chart.seriesList) {
        [chart deleteSeries:s];
    }
    chart.usingRightToLeft = NO;
    chart.minimalHitRadius = 4;
    chart.chartArea.borderColor = [UIColor whiteColor];
    chart.chartArea.backgroundColor = [UIColor whiteColor];
    chart.chartArea.background = [SolidColorBrush solidColorBrushWithColor:[UIColor whiteColor]];
    // Создаем источник данных
    datasource = [[DataSource alloc] init];
    [chart setDataSource :datasource];
    [self setChartSettings];
    [self drawAllSeries];
    // Задаем ссылку на источник данных
    [chart setDelegate:self];
    // Задаем для источника данных максимальное и минимальное значения границы по оси Y
    [datasource prepare];
    [chart forceDataUpdate];
    // Выполняем пользовательский пример
    [self executeExample];
    // Отображаем диаграмму
    [self.view addSubview:chart];
}
// Функция для выполнения примера
-(void) executeExample{
};
- (void)drawAllSeries
{
    [chart deleteAllSeries];
    int seriesCount = datasource.countSeries;
    for (int i = 0; i < seriesCount; ++i)
    {
        axisType = ValueAxisAbsolute;
        hideAxis = NO;
        BubbleSeries *ser = [[BubbleSeries new] autorelease];
        ser.backgroundColor = [UIColor blackColor];
        ser.marker.borderThickness = 1;
        ser.marker.borderColor = [UIColor blackColor];
        ser.marker.shape = MarkerShapeCircle;
        ser.renderTrace = NO;
        ser.color = [UIColor blueColor];
        ser.thickness = 2;
        UIColor *color = [m_colors objectAtIndex:i % [m_colors count]];
        radialBrush = [RadialGradientBrush new];
        GradientStop *st1 = [[[GradientStop alloc] initWithColor:[UIColor whiteColor] offset:0.1] autorelease];
        GradientStop *st2 = [GradientStop gradientStopWithColor:color offset:1.0];
        [radialBrush setGradientStops:[NSMutableArray arrayWithObjects:st1,st2, nil]];
        radialBrush.center = CGPointMake(0.5, 0.5);
        radialBrush.opacity = 1.0;
        RadialGradientBrush *brush = [radialBrush autorelease] ;
        [[radialBrush.gradientStops objectAtIndex:1] setColor:color];
        [ser.marker setBackground:brush];
        ser.shadowOffset  = CGSizeMake(0, 0);
        ser.showShadow = YES;
        ser.dataIndex = i;
        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;
}
- (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 isKindOfClass:[BubblePoint class]])
        {
            NSLog(@"%@",[((BubblePoint *)pt).marker dumpConfigurationToDict]);
        }
        NSLog(@"%@",pt.series);
        NSLog(@"%d",pt.noValue);
        if (pt.chartLabel)
        {
            pt.chartLabelVisible = !pt.chartLabelVisible;
            if (pt.chartLabelVisible)
            {
                [pt moveAboveAllByZOrder];
                ((BubblePoint *)pt).r *= 1.1;
                ((BubblePoint *)pt).marker.borderThickness = 2;
            }
            else
            {
                [pt restoreZOrder];
                ((BubblePoint *)pt).r /= 1.1;
                ((BubblePoint *)pt).marker.borderThickness = 1;
            }
        }
        [chart setNeedsLayout];
    }
    else
    {
        ((TimeAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisTypeTimeline]]).index++;
    }
    
    
    [chart setNeedsDisplay];
}
- (void)setChartSettings
{
    ValueAxis *axisX = (ValueAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisLineX]];
    axisX.axisThickness = 1;  // Толщина оси X
    axisX.majorTicks.thickness = 0; // Толщина основных делений на оси Х
    axisX.minorTicks.thickness = 0; // Толщина дополнительных делений на оси Х
    axisX.startOffset = -0.1;
    ValueAxis *axisY = (ValueAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisLineY]];
    axisY.startOffset = -0.1;
    axisY.axisThickness = 1; // Толщина оси Y
    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];
    if(outputInfo){
        NSLog(@"%f",axisY.maxOffset);
        NSLog(@"%f",axisY.pointsVisible);
    }
    // Определяем параметры делений оси
    AxisTicks *majorTics = ((ValueAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisLineY]]).majorTicks;
    ((ValueAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisLineY]]).minorTicks = majorTics;
    // Определяем ось для пузырьков
    RadialAxis *radAxis = [chart.axes objectForKey:[NSNumber numberWithInt:AxisTypeR]];
    radAxis.maxSize = 50; // Максимальный размер пузырька
    radAxis.minSize = 10; // Минимальный размер пузырька
    radAxis.visible = YES;
    // Определяем параметры временной шкалы
    TimeAxis *timeAxis = ((TimeAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisTypeTimeline]]);
    timeAxis.visible = YES;
    timeAxis.delegate = chart;
    timeAxis.minIndex = 0;
    timeAxis.maxIndex = 5;
    timeAxis.jumpTime = AnimateTypeFast;
    timeAxis.font = [UIFont fontWithName:@"Times New Roman" size:14];
    timeAxis.label.text = @"TimeAxis";
    timeAxis.delayTime = AnimateTypeFastest;
    timeAxis.minTickSpacing = 10.0;
    timeAxis.tickColor = [UIColor blueColor];
    if(outputInfo)
        NSLog(@"%d",timeAxis.axisType);
    Thickness th = {10,0,0,20}; // Отступы
    chart.legend.margin = th; // Отступы для легенды
    th.bottom = 0;
    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 = (Alignment)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");
}
@end

См. также:

Создание пузырьковой диаграммы