Описание: определяются параметры диаграммы и анимации.
#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/ChartPoint.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<ChartTouchesDelegate,ChartAnimationDelegate>{
Chart *chart;
float max;
float min;
NSMutableDictionary *m_numberFormat;
int axisType;
BOOL hideAxis;
int chartType;
NSArray *m_colors;
DataSource *datasource;
BOOL swipedSelection;
CGPoint point;
double angle;
int rotation_count;
}
- (ChartLabel *)createDefaultLabel;
- (void) setChartSettings;
- (void) drawAllSeries;
@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.plotArea.gridTopMost = YES;
chart.plotArea.axesTopMost = YES;
chart.plotArea.selectionEnabled = YES;
chart.plotArea.selectionStart = 0.25;
chart.plotArea.selectionEnd = 0.75;
chart.plotArea.selectionDelegate = self;
chart.plotArea.notelineEnabled = YES;
chart.plotArea.notelineLabel.minWidth = 400;
chart.plotArea.notelineThickness = 1.0;
chart.plotArea.pieZoom = 1.0;
chart.plotArea.isAxisBottom = NO;
chart.plotArea.axisPosition = 0.0;
chart.plotArea.notelineLabel.font = [UIFont fontWithName:@"Arial" size:12];
GradientStop *st1 = [GradientStop gradientStopWithColor:[UIColor blueColor] offset:0.7];
GradientStop *st2 = [GradientStop gradientStopWithColor:[UIColor blackColor] offset:1.0];
LinearGradientBrush *linGr = [[LinearGradientBrush new] autorelease];
linGr.startPoint = CGPointMake(0.0,0.0);
linGr.endPoint = CGPointMake(0.0, 1.0);
[linGr.gradientStops addObject:st1];
[linGr.gradientStops addObject:st2];
chart.plotArea.selectionBrush = linGr;
SolidColorBrush *solidBrush = [SolidColorBrush new];
solidBrush.color = [UIColor blackColor];
chart.plotArea.selectionSliderBrush = [solidBrush autorelease];
// Определяем параметры заголовка
chart.caption.text = @"Диаграмма";
chart.caption.textColor = [UIColor blackColor];
chart.caption.maxTextLength = 140;
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];
[chart setDataSource:datasource];
// Задаем у источника данных максимальное и минимальное значения по оси Y
[datasource prepare];
[self setChartSettings];
[self drawAllSeries];
// Выполняем пользовательский пример
[self executeExample];
[self.view addSubview:chart];
angle = 0.0;
rotation_count = 0;
}
// Функция для выполнения примера
-(void) executeExample{
};
- (void)drawAllSeries
{
[chart deleteAllSeries];
int seriesCount = datasource.countSeries;
GradientStop *grStop = [GradientStop gradientStopWithColor:[UIColor blackColor] offset:1.0];
for (int i = 0; i < seriesCount; ++i)
{
LinearGradientBrush *grBrush = [[LinearGradientBrush new] autorelease];
grBrush.startPoint = CGPointMake(0.0, 0.0);
grBrush.endPoint = CGPointMake(1.0, 0.0);
GradientStop *grSt = [[GradientStop new] autorelease];
grSt.color = [m_colors objectAtIndex:i%[m_colors count]];
grSt.offset = 0.6;
[grBrush.gradientStops addObject:grSt];
[grBrush.gradientStops addObject:grStop];
ColumnSeries *ser = [[ColumnSeries new] autorelease];
[ser setBackground:grBrush];
ser.dataIndex = i;
ser.fillRatio = 0.8;
ser.defaultLabel = [self createDefaultLabel];
[chart addSeries:ser];
}
[chart forceDataUpdate];
for (ColumnSeries *cs in chart.seriesList)
{
for (ColumnPoint *cp in cs.points.allValues) {
cp.borderColor = [UIColor blackColor];
cp.borderRadius = 6.0;
cp.borderThickness = 1.0;
}
}
((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)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.axisLabelsVisible = YES;
axisY.axisLineVisible = YES;
axisY.tickLabelLineBreak = YES;
axisY.axisThickness = 1; // Толщина оси
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.majorTicks.thickness = 1;
axisY.majorTicks.size = 3;
axisY.majorTicks.type = AxisTickBoth;
axisY.majorTicks.color = [UIColor blackColor];
axisY.majorTicks.visible = YES;
axisY.minorTicks.thickness = 0;
axisY.startOffset = 0.0;
axisY.endOffset = 0.0;
axisY.minTickSpacing = 2.0;
axisY.isUserStep = YES;
axisY.userStep = 5.0;
axisY.showMaxValue = YES;
NSMutableArray *interplacedBackground = [NSMutableArray new];
for(int i=0;i < [m_colors count]; i++)
{
SolidColorBrush *b = [SolidColorBrush new];
b.color = [UIColor colorWithIntRed:(250-i*5) green:(250-i*5) blue:250 alpha:255];
[interplacedBackground addObject:[b autorelease]];
}
axisY.interlacedBackground = interplacedBackground;
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 = 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;
return result;
}
- (void)chartTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event sender:(id)sender{}
- (void)chartTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event sender:(id)sender{}
-(void)chartTouchesLongPressInView:(UIView *)v // Событие возникает при нажатии на экран в течение пары секунд
{
// Обновляем график
[chart forceDataUpdate];
}
- (void)chartTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event sender:(id)sender{}
- (void)chartTouchesPinchBeganInView:(UIView *)v withScale:(double)scale velocity:(double)velocity{}
// Перемещение выделения.
// Возникает при нажатом ALT и при перемещении мышки вверх-вниз
- (void)chartTouchesPinchChangedInView:(UIView *)v withScale:(double)scale velocity:(double)velocity
{
if (chart.plotArea.selectionStart >= 0.0)
{
chart.plotArea.selectionStart -= 0.01*velocity;
if (chart.plotArea.selectionStart < 0.0)
{
chart.plotArea.selectionStart = 0.0;
}
}
if (chart.plotArea.selectionEnd <= 1.0)
{
chart.plotArea.selectionEnd += 0.01*velocity;
if(chart.plotArea.selectionEnd > 1.0)
{
chart.plotArea.selectionEnd = 1.0;
}
}
[chart setNeedsLayout];
}
- (void)chartTouchesPinchEndedInView:(UIView *)v withScale:(double)scale velocity:(double)velocity
{
}
- (void)chartTouchesRotationBeganInView:(UIView *)v withRotation:(double)rotation velocity:(double)velocity // Начало вращения
{
NSLog(@"Current angle is %f", angle);
}
- (void)chartTouchesRotationChangedInView:(UIView *)v withRotation:(double)rotation velocity:(double)velocity
{}
- (void)chartTouchesRotationEndedInView:(UIView *)v withRotation:(double)rotation velocity:(double)velocity // Окончание вращения
{
double tmp = (rotation * 180) / M_PI; // Угол поворота, в градусах
angle += tmp;
NSLog(@"Current angle is %f delta is %f",angle,tmp);
}
- (void)chartSelectionChangedInPlotArea:(ChartPlotArea *)plotArea
{
NSLog(@"Selection area changed");
}
- (void)chartTouchesTapInView:(UIView *)v withPoint:(CGPoint)point
{
UIView *sender = [v hitTest:point withEvent:nil];
if ([sender isKindOfClass:[ChartPoint class]])
{
ChartPoint *pt = (ChartPoint *)sender;
pt.showShadow = !pt.showShadow;
pt.shadowRadius = 10.0;
pt.shadowColor = [UIColor blueColor];
pt.shadowOffset = CGSizeMake(1.0, 0.0);
pt.shadowOpacity = 1.0;
if (pt.chartLabel)
{
pt.chartLabelVisible = !pt.chartLabelVisible;
if (pt.chartLabelVisible)
{
[pt moveAboveAllByZOrder];
}
else
{
[pt restoreZOrder];
}
}
[chart setNeedsLayout];
}
}
- (void)chartTouchesPanBeganInView:(UIView *)v withTranslation:(CGPoint)translation velocity:(CGPoint)velocity // Начало перетаскивания
{
NSLog(@"BEGIN_PAN");
}
- (void)chartTouchesPanChangedInView:(UIView *)v withTranslation:(CGPoint)translation velocity:(CGPoint)velocity // Если перетаскиваем, то в столбце диаграммы меняется размер
{
UIView *seriesPoint = [v hitTest:point withEvent:nil]; // Получаем столбец
if([seriesPoint isKindOfClass:[ChartPoint class]])
{
if(velocity.y > 0){ // Если двигаем вниз, уменьшаем размер столбца
NSLog(@"-");
}
else
{ // иначе увеличиваем
NSLog(@"+");
}
[chart setNeedsLayout];
}
}
- (void)chartTouchesPanEndedInView:(UIView *)v withTranslation:(CGPoint)translation velocity:(CGPoint)velocity
{
NSLog(@"END_PAN");
}
- (void)chartTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event sender:(id)sender // Если касание было прервано другим событием
{
UITouch *touch = [[touches allObjects] objectAtIndex:0]; // Получаем касание
point = [touch locationInView:nil]; // Находим точку касания
}
@end
См. также: