Описание: определяются параметры диаграммы и анимации.
#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 "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>{
Chart *chart;
float max;
float min;
NSMutableDictionary *m_numberFormat;
int axisType;
BOOL hideAxis;
int chartType;
NSArray *m_colors;
DataSource *datasource;
}
- (ChartLabel *)createDefaultLabel;
- (void) setChartSettings;
- (void) drawAllSeries;
- (NSString *) animationClassName:(id) sender;
- (void) rotate;
- (void) move;
- (void) scale;
- (void) fade;
- (void) movePie;
@end
#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.delegate = self;
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.font = [UIFont fontWithName:@"Arial" size:12];
chart.legend.legendOrientation = LegendOrientationBottom;
chart.legend.textColor = [UIColor blackColor];
chart.legend.maxEntriesCount = 5;
// Создаем источник данных
datasource = [[DataSource alloc] init];
[self setChartSettings];
[self drawAllSeries];
// Задаем ссылку на источник данных
[chart setDataSource :datasource];
// Определяем параметры кнопок, запускающих анимацию
UIToolbar *bar = [[UIToolbar new] autorelease];
bar.frame = CGRectMake(0, 0, 600, 40);
[bar setBarStyle:UIBarStyleDefault];
UIBarButtonItem *rotate = [[[UIBarButtonItem alloc] initWithTitle:@"вращение" style:UIBarButtonItemStyleDone target:self action:@selector(rotate)] autorelease];
UIBarButtonItem *movePie = [[[UIBarButtonItem alloc] initWithTitle:@"движение части" style:UIBarButtonItemStyleDone target:self action:@selector(movePie)] autorelease];
UIBarButtonItem *move = [[[UIBarButtonItem alloc] initWithTitle:@"движение" style:UIBarButtonItemStyleDone target:self action:@selector(move)] autorelease];
UIBarButtonItem *fade = [[[UIBarButtonItem alloc] initWithTitle:@"затухание" style:UIBarButtonItemStyleDone target:self action:@selector(fade)] autorelease];
UIBarButtonItem *scale = [[[UIBarButtonItem alloc] initWithTitle:@"масштабирование" style:UIBarButtonItemStyleDone target:self action:@selector(scale)] autorelease];
UIBarButtonItem *item = [[[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil] autorelease];
UIBarButtonItem *spacer = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease];
[bar setItems:[NSArray arrayWithObjects:rotate,movePie,move,fade,scale,spacer,item,nil]];
chart.frame = CGRectMake(0, 40, chart.frame.size.width, chart.frame.size.height - 40);
// Задаем для источника данных максимальное и минимальное значения границы по оси Y
[datasource prepare];
[chart forceDataUpdate]; // Обновляем данные. Анимация выключается
chart.animationsStartingEnabled = YES; //Включаем анимацию
// Выполняем пользовательский пример
[self executeExample];
// Отображаем диаграмму
[self.view addSubview:bar];
[self.view addSubview:chart];
}
// Функция для выполнения примера
-(void) executeExample{
};
- (void)drawAllSeries
{
[chart deleteAllSeries];
int seriesCount = datasource.countSeries;
for (int i = 0; i < seriesCount; ++i)
{
PieSeries *ser = [[PieSeries new] autorelease];
SolidColorBrush *brush = [[SolidColorBrush new] autorelease];
brush.color =[m_colors objectAtIndex:i % [m_colors count]];
[ser setBackground:brush];
ser.dataIndex = i;
ser.holeRadius = 0.5;
ser.defaultLabel = [self createDefaultLabel];
[chart addSeries:ser];
}
[chart forceDataUpdate];
((ValueAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisLineX]]).valueAxisType = ValueAxisAbsolute;
((ValueAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisLineY]]).valueAxisType = ValueAxisAbsolute;
((ValueAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisLineX]]).visible = YES;
((ValueAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisLineY]]).visible = YES;
}
- (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];
else
[pt restoreZOrder];
}
[chart setNeedsLayout];
}
}
- (void)setChartSettings
{
((ValueAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisLineX]]).axisThickness = 1; // Толщина оси X
AxisTicks *t = [[AxisTicks alloc] initWithColor:[UIColor blackColor] size:3 thickness:3];
((ValueAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisLineX]]).majorTicks = t; // Основные деления на оси Х
((ValueAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisLineX]]).minorTicks.thickness = 0; // Толщина дополнительных делений на оси Х
// Параметры оси Y
ValueAxis *axisY = ((ValueAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisLineY]]);
axisY.axisThickness = 1; // Толщина оси
// Определяем параметры основных засечек оси
AxisTicks *Ticks = [AxisTicks new];
Ticks.type = AxisTickOuter;
Ticks.visible = YES;
Ticks.color = [UIColor blueColor];
Ticks.thickness = 1;
Ticks.size = 3;
axisY.majorTicks = Ticks;
// Определяем параметры промежуточных засечек оси
AxisTicks *MinTick = [AxisTicks axisTicksWithColor:[UIColor brownColor] size:2 thickness:1];
axisY.minorTicks=MinTick;
// Определяем параметры сетки и шрифта оси
axisY.showGrid = YES; // Показываем сетку
axisY.gridThickness = 1; // Толщина сетки
axisY.gridColor = ColorWithRGBA(200, 200, 200, 255);
axisY.font = [UIFont fontWithName:@"Arial" size:14];
axisY.textColor = [UIColor blackColor];
axisY.axisLineVisible = YES;
axisY.color = [UIColor blueColor];
// Определяем параметры временной шкалы
TimeAxis *timeAxis = ((TimeAxis *)[chart.axes objectForKey:[NSNumber numberWithInt:AxisTypeTimeline]]);
timeAxis.visible = NO;
Thickness th = {10,0,0,20}; // Отступы
chart.legend.margin = th; // Отступы для легенды
th.bottom = 10;
th.left = th.right = th.top = 0;
chart.chartArea.padding = th; // Отступы для области диаграмм
chart.plotArea.selectionEnabled = NO;
}
- (ChartLabel *)createDefaultLabel
{
ChartLabel *result = [[[ChartLabel alloc] initWithFrame:CGRectZero] autorelease]; // Создаем метку
SolidColorBrush *br = [[SolidColorBrush new] autorelease];
br.color = [UIColor whiteColor];
result.background = br; // Задаем цвет
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;
result.hasFootNoteLine = YES;
result.hasHorizontalNoteLine = YES;
result.hasVerticalNoteLine = YES;
result.noteLineColor = [UIColor redColor];
result.noteLineThickness = 2.0;
result.visible = YES;
return result;
}
- (void) rotate
{
NSArray *series = [chart seriesList]; // Получаем все ряды
ChartAnimationRotate *rotate = [[ChartAnimationRotate alloc] initWithAnimationName:@"rotate"]; // Создаем анимацию вращения с именем "rotate"
rotate.angle = -6.28; // Угол поворота в радианах (если угол < 0, то вращение по часовой стрелке, иначе против часовой)
rotate.startDelay = 0; // Время задержки в секундах
rotate.duration = 3; // Продолжительность в секундах
rotate.delegate = self;
// Применяем анимацию ко всем рядам
for (ChartSeries *ser in series) {
[ser addAnimation:rotate];
}
// Запускаем анимацию
[chart forceUpdateAnimations];
}
- (void)movePie
{
NSArray *series = [chart seriesList]; // Получаем все ряды
PieSeries *ser = [series objectAtIndex:1];
ChartAnimationPieMove *move = [[ChartAnimationPieMove alloc] initWithAnimationName:@"movePie"];// Анимация смещения сектора круговой диаграммы
move.delegate = self;
if(ser.cutoutLength != 0)
{
move.shift = 50;
ser.cutoutLength = 0;
}
else
{
move.shift = -50;
ser.cutoutLength = 50;
}
move.startDelay = 0;
move.duration = 2;
[ser addAnimation:move];
[chart forceUpdateAnimations];
}
- (void)move
{
NSArray *series = [chart seriesList]; // Получаем все ряды
ChartAnimationMove *move = [[ChartAnimationMove alloc] initWithAnimationName:@"move"]; // Анимация перемещения
move.offset = CGPointMake(100, 100); // Точка, из которой выполняется перемещение
move.startDelay = 0;
move.duration = 3;
move.delegate = self;
for (ChartSeries *ser in series) {
[ser addAnimation:move];
}
[chart forceUpdateAnimations];
}
- (void) fade
{
NSArray *series = [chart seriesList]; // Получаем все ряды
ChartAnimationFade *fade = [[ChartAnimationFade alloc] initWithAnimationName:@"fade"]; // Анимация изменения прозрачности
fade.alpha = 0.1; // Начальное значение прозрачности
fade.startDelay = 0;
fade.duration = 3;
fade.delegate = self;
for (ChartSeries *ser in series) {
[ser addAnimation:fade];
}
[chart forceUpdateAnimations];
}
- (void) scale
{
NSArray *series = [chart seriesList]; // Получаем все ряды
ChartAnimationScale *scale = [[ChartAnimationScale alloc] initWithAnimationName:@"scale"]; // Анимация масштабирования
scale.scale = 0.1; // Начальный масштаб
scale.startDelay = 0;
scale.duration = 3;
scale.delegate = self;
ChartAnimationScale *scale2 = [[ChartAnimationScale alloc] initWithAnimationName:@"scale 2"];
scale2.scale = 0.1;
scale2.startDelay = 2;
scale2.duration = 3;
scale2.delegate = self;
[[series objectAtIndex:0] addAnimation:scale];
[[series objectAtIndex:2] addAnimation:scale2];
[chart forceUpdateAnimations];
}
// Анимация завершилась
- (void)animationComplete:(id)sender
{
NSArray *subviews = [self.view subviews]; // Получаем все отображаемые элементы
UIToolbar *bar = (UIToolbar *)[subviews objectAtIndex:0]; // Получаем ссылку на панель с кнопками
((UIBarButtonItem *)[bar.items lastObject]).title = [NSString stringWithFormat:@"Завершено %@",[self animationClassName:sender]]; // Выводим надпись
}
- (void)animationStarted:(id)sender
{
NSArray *subviews = [self.view subviews];
UIToolbar *bar = (UIToolbar *)[subviews objectAtIndex:0];
((UIBarButtonItem *)[bar.items lastObject]).title = [NSString stringWithFormat:@"Начато %@",[self animationClassName:sender]];
}
// Получаем на основании имени класса тип анимации
- (NSString *)animationClassName:(id)sender
{
NSString *str = NSStringFromClass([sender class]); // Получаем имя класса в виде строки
NSRange range = [NSStringFromClass([sender class]) rangeOfString:@"ChartAnimation"]; // Получаем вхождение подстроки в строку
int pos = range.length;
NSString *animationName = [str substringFromIndex:pos]; // Получаем подстроку начиная с позиции pos
if([animationName isEqual: @"Rotate"])
animationName = @"Вращение";
if([animationName isEqual: @"PieMove"])
animationName = @"Движение части";
if([animationName isEqual: @"Move"])
animationName = @"Движение";
if([animationName isEqual: @"Fade"])
animationName = @"Затухание";
if([animationName isEqual: @"Scale"])
animationName = @"Масштабирование";
return animationName; // Возвращаем имя типа анимации (Rotate,Move и т.д.)
}
@end
См. также: