Jun 21, 2011

How To implement Graphs In Iphnoe



Many thanks to habrauser snobit for sharing his sources for GraphView, the Cocoa component that served as the basis for S7GraphView.
Выражаю свою искреннюю благодарность хабраюзеру snobit за предоставление исходников для GraphView - Cocoa компонента, который послужил основой для создания S7GraphView.
Features
Can change background color, grid line colors as well as regulate their visibility, axis text colors.
Can display information text above the graph. You can set its color as well.
Can display one or several graphs at a time.
Easy to customize text for axis.
Half-automatic logic.
Using the Component
If you have a decent experience with UITableView or any other Cocoa Touch component that takes its data via a data-source, it will be easy for you to catch up with S7GraphView since it supports that ideology too.

For instructions on how to throw in the component to your project, please, refer to my another initiative - s7ratingview. I will go straight to code now.

N.B. In time the instructions will be much more verbose, but this is all I have time to squeeze out for now.

First you need to include a proper import. Open your *.h file:

#import "S7GraphView.h"
Now let the compiler know you are going to implement S7GraphViewDataSource protocol:

@interface MainViewController : UIViewController {
}
...
@end
Go to the associated *.m file and implement the methods S7GraphViewDataSource requires:

- (NSUInteger)graphViewNumberOfPlots:(S7GraphView *)graphView {
/* Return the number of plots you are going to have in the view. 1+ */
}

- (NSArray *)graphViewXValues:(S7GraphView *)graphView {
/* An array of objects that will be further formatted to be displayed on the X-axis.
The number of elements should be equal to the number of points you have for every plot. */
}

- (NSArray *)graphView:(S7GraphView *)graphView yValuesForPlot:(NSUInteger)plotIndex {
/* Return the values for a specific graph. Each plot is meant to have equal number of points.
And this amount should be equal to the amount of elements you return from graphViewXValues: method. */
}
Optionally you can implement this method as well:

- (BOOL)graphView:(S7GraphView *)graphView shouldFillPlot:(NSUInteger)plotIndex;
It explains the graph-view which graph should be rendered with filled space below it. Usually you'll want it to be the plot with index = 0 to not overlap other plots.

N.B. In the future revision it is very possible that the fill color will be customizable.

For example in viewDidLoad method add such initialization (it was used to create the graph in the video):

NSNumberFormatter *numberFormatter = [NSNumberFormatter new];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMinimumFractionDigits:0];
[numberFormatter setMaximumFractionDigits:0];

self.graphView.yValuesFormatter = numberFormatter;

NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];

self.graphView.xValuesFormatter = dateFormatter;

[dateFormatter release];
[numberFormatter release];

self.graphView.backgroundColor = [UIColor blackColor];

self.graphView.drawAxisX = YES;
self.graphView.drawAxisY = YES;
self.graphView.drawGridX = YES;
self.graphView.drawGridY = YES;

self.graphView.xValuesColor = [UIColor whiteColor];
self.graphView.yValuesColor = [UIColor whiteColor];

self.graphView.gridXColor = [UIColor whiteColor];
self.graphView.gridYColor = [UIColor whiteColor];

self.graphView.drawInfo = NO;
self.graphView.info = @"Load";
self.graphView.infoColor = [UIColor whiteColor];
When you need to update the data, make this call:

[self.graphView reloadData];
Мажлівасці
Можа змяняць колер тлу, колер лініяў сеткі як і іх бачнасць, колер тэксту подпісаў на восях коордынатаў.
Можа адлюстроўваць інформацыйны тэкст над графікам. Вы таксама можаце ўсталяваць ягоны колер.
Можа адлюстроўваць адзін ці некалькі графікаў адначасова.
Проста кастомайзіць тэкст подпісаў на восях коордынатаў.
Напаўаўтаматычная лёгіка.
Ужыванне компонэнту
Калі вы маеце багата досведу з UITableView ці любым іншым компонэнтам Cocoa Touch, каторы атрымоўвае дадзеныя з data-source, вам будзе лёгка пачаць працаваць і з S7GraphView, бо той падтрымоўвае тую-ж самую ідэолёгію.

За інструкцыямі па тым, як укінуць компонэнт у вашы проект, звяртайцеся, калі ласка, да маёй іншай ініцыятывы - s7ratingview. Зараз-жа я адразу перайду да коду.

N.B. З цягам часу інструкцыі стануць падрабязнейшымі, але пакуль гэта ўсё, што я змог з сябе выціснуць праз нястачу часу.

Спярша трэ ўточыць правільны import. Адкрыйце свой файл *.h і дадайце:

#import "S7GraphView.h"
Цяпер дайце компілятару зразумець, што вы збіраецеся рэалізаваць протокол S7GraphViewDataSource:

@interface MainViewController : UIViewController {
}
...
@end
Пералучыцеся на адпаведны файл *.m і рэалізуйце мэтоды, патрабаваныя S7GraphViewDataSource:

- (NSUInteger)graphViewNumberOfPlots:(S7GraphView *)graphView {
/* Вярніце колькасць графікаў, каторыя маюць быць адлюстраваныя ў view. 1+ */
}

- (NSArray *)graphViewXValues:(S7GraphView *)graphView {
/* Массыў об'ектаў, каторыя пазней будуць сфарматаваныя, каб быць адлюстраванымі на восі X.
Колькасць элементаў мае быць роўная колькасці кропак у кожным графіку.
*/
}

- (NSArray *)graphView:(S7GraphView *)graphView yValuesForPlot:(NSUInteger)plotIndex {
/* Вярніце значанні для конкрэтнага графіку. Маецца на ўвазе, што кожны графік будзе мець аднолькавую колькасць кропак.
І гэтая колькасць мае быць роўнай колькасці элементаў, каторую вы вяртаеце з мэтоду graphViewXValues:.
}
Опцыянальна вы можаце таксама рэалізаваць наступны мэтод:

- (BOOL)graphView:(S7GraphView *)graphView shouldFillPlot:(NSUInteger)plotIndex;
Гэтак вы тлумачыце graph-view, які графік мае быць адлюстраваны з запоўненнай пад ім вобласцю. Звычайна гэта будзе графік з index = 0, каб не перакрыць астатніх графікаў.

N.B. У будучых рэвізіях цалкам мажліва, што колер запаўнення можна будзе змяняць.

Прыкладам, у мэтодзе viewDidLoad можаце дадаць такую ініцыялізацыю (менавіта гэткая была скарыстана, каб стварыць графік на відэо):

NSNumberFormatter *numberFormatter = [NSNumberFormatter new];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMinimumFractionDigits:0];
[numberFormatter setMaximumFractionDigits:0];

self.graphView.yValuesFormatter = numberFormatter;

NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];

self.graphView.xValuesFormatter = dateFormatter;

[dateFormatter release];
[numberFormatter release];

self.graphView.backgroundColor = [UIColor blackColor];

self.graphView.drawAxisX = YES;
self.graphView.drawAxisY = YES;
self.graphView.drawGridX = YES;
self.graphView.drawGridY = YES;

self.graphView.xValuesColor = [UIColor whiteColor];
self.graphView.yValuesColor = [UIColor whiteColor];

self.graphView.gridXColor = [UIColor whiteColor];
self.graphView.gridYColor = [UIColor whiteColor];

self.graphView.drawInfo = NO;
self.graphView.info = @"Load";
self.graphView.infoColor = [UIColor whiteColor];
Пры неабходнасці абнавіць дадзеныя, зрабіце такі выклік:

[self.graphView reloadData];


For Source Code Clik Here

No comments:

Post a Comment