code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
//
// TMErrors.m
// TestMerge
//
// Created by Barry Wark on 5/27/09.
// Copyright 2009 Physion Consulting LLC. All rights reserved.
//
NSString * const TMErrorDomain = @"TMErrorDomain";
const NSInteger TMPathError = 1;
const NSInteger TMCoreDataError = 2;
| 08iteng-ipad | TestMerge/TMErrors.m | Objective-C | bsd | 264 |
#!/bin/bash
mkdir -p Library/SDKs/CorePlotSDK
mkdir -p Library/Frameworks
mkdir -p Library/Developer/Shared/Documentation/DocSets
mkdir -p CorePlot/Binaries/iOS/CorePlot
unzip CorePlot/Binaries/iOS/CorePlot.zip -d CorePlot/Binaries/iOS/CorePlot
cp -r CorePlot/Binaries/iOS/CorePlot/CorePlotSDK/* Library/SDKs/CorePlotSDK
rm -r CorePlot/Binaries/iOS/CorePlot
cp -r CorePlot/Binaries/MacOS/CorePlot.framework Library/Frameworks
cp -r CorePlot/Documentation/* Library/Developer/Shared/Documentation/DocSets
chown -R root:admin Library
/Developer/usr/bin/packagemaker --doc "Core Plot Install.pmdoc" --out "Core Plot Install.pkg"
rm -r Library
| 08iteng-ipad | packaging/prepare.sh | Shell | bsd | 647 |
{\rtf1\ansi\ansicpg1252\cocoartf1038\cocoasubrtf290
{\fonttbl\f0\fswiss\fcharset0 Helvetica;\f1\fmodern\fcharset0 Courier;}
{\colortbl;\red255\green255\blue255;}
\margl1440\margr1440\vieww9000\viewh8400\viewkind0
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural
\f0\fs36 \cf0 Five Steps to CorePlot
\fs24 \
\
1. Copy the
\b CorePlotSDK
\b0 directory to
\b ~/Library/SDKs/
\b0 \
\
2. Add to your project's .PCH file:\
\
\f1 #import <CorePlot/CorePlot.h>
\f0 \
\
3. Open Project -> Edit Project Settings and for
\b All Configurations
\b0 :\
\
3a. Add to
\b Additional SDKS
\b0 : \
\
\f1 $HOME/Library/SDKs/CorePlotSDK/$\{PLATFORM_NAME\}.sdk
\f0 \
\
3b. Add to
\b Other Linker Flags
\b0 :\
\
\f1 -ObjC -all_load -lCorePlot
\f0 \
\
4. Add the
\b QuartzCore
\b0 framework to the project.\
\
5. Add a CPGraph to your application.} | 08iteng-ipad | READMEs/README for SDK Install.rtf | Rich Text Format | bsd | 905 |
{\rtf1\ansi\ansicpg1252\cocoartf1038\cocoasubrtf320
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
\paperw12240\paperh15840\margl1440\margr1440\vieww17480\viewh10900\viewkind0
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural
\f0\fs36 \cf0 To Install Documentation
\fs24 \
\
1. Quit Xcode\
\
2. Copy the
\b com.CorePlot.Framework.docset
\b0 bundle into
\b ~/Library/Developer/Shared/Documentation/DocSets/
\b0 \
\
3. Launch Xcode, and browse Core Plot documentation in the Documentation browser} | 08iteng-ipad | READMEs/README for Docs Install.rtf | Rich Text Format | bsd | 597 |
#import <Cocoa/Cocoa.h>
#import <CorePlot/CorePlot.h>
@interface AxisDemoController : NSObject {
IBOutlet CPLayerHostingView *hostView;
}
@end
| 08iteng-ipad | examples/CPTestApp/Source/AxisDemoController.h | Objective-C | bsd | 150 |
#import "Controller.h"
#import <CorePlot/CorePlot.h>
static const CGFloat kZDistanceBetweenLayers = 20.0;
static NSString * const bindingsPlot = @"Bindings Plot";
static NSString * const dataSourcePlot = @"Data Source Plot";
static NSString * const barPlot1 = @"Bar Plot 1";
static NSString * const barPlot2 = @"Bar Plot 2";
@interface Controller ()
-(void)setupGraph;
-(void)setupAxes;
-(void)setupScatterPlots;
-(void)positionFloatingAxis;
-(void)setupBarPlots;
@end
#pragma mark -
@implementation Controller
@synthesize xShift;
@synthesize yShift;
@synthesize labelRotation;
+(void)initialize
{
[NSValueTransformer setValueTransformer:[[CPDecimalNumberValueTransformer new] autorelease] forName:@"CPDecimalNumberValueTransformer"];
}
-(void)dealloc
{
[graph release];
[super dealloc];
}
-(void)awakeFromNib
{
[super awakeFromNib];
self.xShift = 0.0;
self.yShift = 0.0;
[self setupGraph];
[self setupAxes];
[self setupScatterPlots];
[self positionFloatingAxis];
[self setupBarPlots];
}
-(id)newObject
{
NSNumber *x1 = [NSDecimalNumber numberWithDouble:1.0 + ((NSMutableArray *)self.content).count * 0.05];
NSNumber *y1 = [NSDecimalNumber numberWithDouble:1.2 * rand()/(double)RAND_MAX + 1.2];
return [[NSMutableDictionary dictionaryWithObjectsAndKeys:x1, @"x", y1, @"y", nil] retain];
}
#pragma mark -
#pragma mark Graph Setup Methods
-(void)setupGraph
{
// Create graph and apply a dark theme
graph = [(CPXYGraph *)[CPXYGraph alloc] initWithFrame:NSRectToCGRect(hostView.bounds)];
CPTheme *theme = [CPTheme themeNamed:kCPDarkGradientTheme];
[graph applyTheme:theme];
hostView.hostedLayer = graph;
// Graph title
graph.title = @"This is the Graph Title";
CPMutableTextStyle *textStyle = [CPMutableTextStyle textStyle];
textStyle.color = [CPColor grayColor];
textStyle.fontName = @"Helvetica-Bold";
textStyle.fontSize = 18.0;
graph.titleTextStyle = textStyle;
graph.titleDisplacement = CGPointMake(0.0, 20.0);
graph.titlePlotAreaFrameAnchor = CPRectAnchorTop;
// Graph padding
graph.paddingLeft = 60.0;
graph.paddingTop = 60.0;
graph.paddingRight = 60.0;
graph.paddingBottom = 60.0;
}
-(void)setupAxes
{
// Setup scatter plot space
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
plotSpace.delegate = self;
// Grid line styles
CPMutableLineStyle *majorGridLineStyle = [CPMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [[CPColor colorWithGenericGray:0.2] colorWithAlphaComponent:0.75];
CPMutableLineStyle *minorGridLineStyle = [CPMutableLineStyle lineStyle];
minorGridLineStyle.lineWidth = 0.25;
minorGridLineStyle.lineColor = [[CPColor whiteColor] colorWithAlphaComponent:0.1];
CPMutableLineStyle *redLineStyle = [CPMutableLineStyle lineStyle];
redLineStyle.lineWidth = 10.0;
redLineStyle.lineColor = [[CPColor redColor] colorWithAlphaComponent:0.5];
// Axes
// Label x axis with a fixed interval policy
CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.majorIntervalLength = CPDecimalFromString(@"0.5");
x.orthogonalCoordinateDecimal = CPDecimalFromString(@"2");
x.minorTicksPerInterval = 2;
x.majorGridLineStyle = majorGridLineStyle;
x.minorGridLineStyle = minorGridLineStyle;
NSArray *exclusionRanges = [NSArray arrayWithObjects:
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(1.99) length:CPDecimalFromFloat(0.02)],
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.99) length:CPDecimalFromFloat(0.02)],
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(2.99) length:CPDecimalFromFloat(0.02)],
nil];
x.labelExclusionRanges = exclusionRanges;
x.title = @"X Axis";
x.titleOffset = 30.0;
x.titleLocation = CPDecimalFromString(@"3.0");
// Label y with an automatic label policy.
CPXYAxis *y = axisSet.yAxis;
y.labelingPolicy = CPAxisLabelingPolicyAutomatic;
y.orthogonalCoordinateDecimal = CPDecimalFromString(@"2");
y.minorTicksPerInterval = 2;
y.preferredNumberOfMajorTicks = 8;
y.majorGridLineStyle = majorGridLineStyle;
y.minorGridLineStyle = minorGridLineStyle;
y.labelOffset = 10.0;
exclusionRanges = [NSArray arrayWithObjects:
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(1.99) length:CPDecimalFromFloat(0.02)],
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.99) length:CPDecimalFromFloat(0.02)],
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(3.99) length:CPDecimalFromFloat(0.02)],
nil];
y.labelExclusionRanges = exclusionRanges;
y.title = @"Y Axis";
y.titleOffset = 30.0;
y.titleLocation = CPDecimalFromString(@"2.7");
// Rotate the labels by 45 degrees, just to show it can be done.
self.labelRotation = M_PI * 0.25;
// Add an extra y axis (red)
// We add constraints to this axis below
CPXYAxis *y2 = [[(CPXYAxis *)[CPXYAxis alloc] initWithFrame:CGRectZero] autorelease];
y2.labelingPolicy = CPAxisLabelingPolicyAutomatic;
y2.orthogonalCoordinateDecimal = CPDecimalFromString(@"3");
y2.minorTicksPerInterval = 0;
y2.preferredNumberOfMajorTicks = 4;
y2.majorGridLineStyle = majorGridLineStyle;
y2.minorGridLineStyle = minorGridLineStyle;
y2.labelOffset = 10.0;
y2.coordinate = CPCoordinateY;
y2.plotSpace = graph.defaultPlotSpace;
y2.axisLineStyle = redLineStyle;
y2.majorTickLineStyle = redLineStyle;
y2.minorTickLineStyle = nil;
y2.labelTextStyle = nil;
y2.visibleRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromInteger(2) length:CPDecimalFromInteger(3)];
// Set axes
graph.axisSet.axes = [NSArray arrayWithObjects:x, y, y2, nil];
}
-(void)setupScatterPlots
{
// Create one plot that uses bindings
CPScatterPlot *boundLinePlot = [[[CPScatterPlot alloc] init] autorelease];
boundLinePlot.identifier = bindingsPlot;
CPMutableLineStyle *lineStyle = [[boundLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.miterLimit = 1.0;
lineStyle.lineWidth = 3.0;
lineStyle.lineColor = [CPColor blueColor];
boundLinePlot.dataLineStyle = lineStyle;
[graph addPlot:boundLinePlot];
[boundLinePlot bind:CPScatterPlotBindingXValues toObject:self withKeyPath:@"arrangedObjects.x" options:nil];
[boundLinePlot bind:CPScatterPlotBindingYValues toObject:self withKeyPath:@"arrangedObjects.y" options:nil];
// Put an area gradient under the plot above
NSString *pathToFillImage = [[NSBundle mainBundle] pathForResource:@"BlueTexture" ofType:@"png"];
CPImage *fillImage = [CPImage imageForPNGFile:pathToFillImage];
fillImage.tiled = YES;
CPFill *areaGradientFill = [CPFill fillWithImage:fillImage];
boundLinePlot.areaFill = areaGradientFill;
boundLinePlot.areaBaseValue = [[NSDecimalNumber one] decimalValue];
// Add plot symbols
CPMutableLineStyle *symbolLineStyle = [CPMutableLineStyle lineStyle];
symbolLineStyle.lineColor = [CPColor blackColor];
CPPlotSymbol *plotSymbol = [CPPlotSymbol ellipsePlotSymbol];
plotSymbol.fill = [CPFill fillWithColor:[CPColor blueColor]];
plotSymbol.lineStyle = symbolLineStyle;
plotSymbol.size = CGSizeMake(10.0, 10.0);
boundLinePlot.plotSymbol = plotSymbol;
// Set plot delegate, to know when symbols have been touched
// We will display an annotation when a symbol is touched
boundLinePlot.delegate = self;
boundLinePlot.plotSymbolMarginForHitDetection = 5.0f;
// Create a second plot that uses the data source method
CPScatterPlot *dataSourceLinePlot = [[[CPScatterPlot alloc] init] autorelease];
dataSourceLinePlot.identifier = dataSourcePlot;
dataSourceLinePlot.cachePrecision = CPPlotCachePrecisionDouble;
lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.lineWidth = 1.0;
lineStyle.lineColor = [CPColor greenColor];
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.dataSource = self;
CPMutableTextStyle *whiteTextStyle = [CPMutableTextStyle textStyle];
whiteTextStyle.color = [CPColor whiteColor];
dataSourceLinePlot.labelTextStyle = whiteTextStyle;
dataSourceLinePlot.labelOffset = 5.0;
dataSourceLinePlot.labelRotation = M_PI_4;
[graph addPlot:dataSourceLinePlot];
// Make the data source line use stepped interpolation
dataSourceLinePlot.interpolation = CPScatterPlotInterpolationStepped;
// Put an area gradient under the plot above
CPColor *areaColor = [CPColor colorWithComponentRed:0.3 green:1.0 blue:0.3 alpha:0.8];
CPGradient *areaGradient = [CPGradient gradientWithBeginningColor:areaColor endingColor:[CPColor clearColor]];
areaGradient.angle = -90.0;
areaGradientFill = [CPFill fillWithGradient:areaGradient];
dataSourceLinePlot.areaFill = areaGradientFill;
dataSourceLinePlot.areaBaseValue = CPDecimalFromString(@"1.75");
// Add some initial data
NSMutableArray *contentArray = [NSMutableArray arrayWithCapacity:100];
for ( NSUInteger i = 0; i < 60; i++ ) {
id x = [NSDecimalNumber numberWithDouble:1.0 + i * 0.05];
id y = [NSDecimalNumber numberWithDouble:1.2 * rand()/(double)RAND_MAX + 1.2];
[contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x, @"x", y, @"y", nil]];
}
self.content = contentArray;
// Auto scale the plot space to fit the plot data
// Extend the y range by 10% for neatness
CPXYPlotSpace *plotSpace = (id)graph.defaultPlotSpace;
[plotSpace scaleToFitPlots:[NSArray arrayWithObjects:boundLinePlot, dataSourceLinePlot, nil]];
CPPlotRange *xRange = plotSpace.xRange;
CPPlotRange *yRange = plotSpace.yRange;
[yRange expandRangeByFactor:CPDecimalFromDouble(1.1)];
plotSpace.yRange = yRange;
// Restrict y range to a global range
CPPlotRange *globalYRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0f) length:CPDecimalFromFloat(6.0f)];
plotSpace.globalYRange = globalYRange;
// set the x and y shift to match the new ranges
CGFloat length = xRange.lengthDouble;
self.xShift = length - 3.0;
length = yRange.lengthDouble;
self.yShift = length - 2.0;
}
-(void)positionFloatingAxis
{
// Position y2 axis relative to the plot area, ie, not moving when dragging
CPConstraints y2Constraints = {CPConstraintNone, CPConstraintFixed};
CPXYAxis *y2 = [graph.axisSet.axes objectAtIndex:2];
y2.isFloatingAxis = YES;
y2.constraints = y2Constraints;
}
-(void)setupBarPlots
{
// Add plot space for horizontal bar charts
CPXYPlotSpace *barPlotSpace = [[CPXYPlotSpace alloc] init];
barPlotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-20.0f) length:CPDecimalFromFloat(200.0f)];
barPlotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-7.0f) length:CPDecimalFromFloat(15.0f)];
[graph addPlotSpace:barPlotSpace];
[barPlotSpace release];
// First bar plot
CPMutableTextStyle *whiteTextStyle = [CPMutableTextStyle textStyle];
whiteTextStyle.color = [CPColor whiteColor];
CPBarPlot *barPlot = [CPBarPlot tubularBarPlotWithColor:[CPColor darkGrayColor] horizontalBars:YES];
barPlot.baseValue = CPDecimalFromFloat(20.0f);
barPlot.dataSource = self;
barPlot.barOffset = CPDecimalFromFloat(-0.25f);
barPlot.identifier = barPlot1;
barPlot.plotRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(7.0)];
barPlot.barLabelTextStyle = whiteTextStyle;
[graph addPlot:barPlot toPlotSpace:barPlotSpace];
// Second bar plot
barPlot = [CPBarPlot tubularBarPlotWithColor:[CPColor blueColor] horizontalBars:YES];
barPlot.dataSource = self;
barPlot.baseValue = CPDecimalFromFloat(20.0f);
barPlot.barOffset = CPDecimalFromFloat(0.25f);
barPlot.cornerRadius = 2.0;
barPlot.identifier = barPlot2;
barPlot.plotRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(7.0)];
barPlot.delegate = self;
[graph addPlot:barPlot toPlotSpace:barPlotSpace];
}
#pragma mark -
#pragma mark Actions
-(IBAction)reloadDataSourcePlot:(id)sender
{
CPPlot *plot = [graph plotWithIdentifier:dataSourcePlot];
[plot reloadData];
}
-(IBAction)removeData:(id)sender
{
NSUInteger index = self.selectionIndex;
if ( index != NSNotFound ) {
[self removeObjectAtArrangedObjectIndex:index];
CPPlot *plot = [graph plotWithIdentifier:dataSourcePlot];
[plot deleteDataInIndexRange:NSMakeRange(index, 1)];
}
}
-(IBAction)insertData:(id)sender
{
NSUInteger index = self.selectionIndex;
if ( index != NSNotFound ) {
[self insertObject:[self newObject] atArrangedObjectIndex:index];
CPPlot *plot = [graph plotWithIdentifier:dataSourcePlot];
[plot insertDataAtIndex:index numberOfRecords:1];
}
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
if ( [plot isKindOfClass:[CPBarPlot class]] )
return 8;
else
return [self.arrangedObjects count];
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSNumber *num;
if ( [plot isKindOfClass:[CPBarPlot class]] ) {
num = [NSDecimalNumber numberWithInt:(index+1)*(index+1)];
if ( [plot.identifier isEqual:barPlot2] )
num = [(NSDecimalNumber *)num decimalNumberBySubtracting:[NSDecimalNumber decimalNumberWithString:@"10"]];
}
else {
num = [[self.arrangedObjects objectAtIndex:index] valueForKey:(fieldEnum == CPScatterPlotFieldX ? @"x" : @"y")];
if ( fieldEnum == CPScatterPlotFieldY ) {
num = [NSNumber numberWithDouble:([num doubleValue] + 1.0)];
}
}
return num;
}
-(CPFill *)barFillForBarPlot:(CPBarPlot *)barPlot recordIndex:(NSUInteger)index
{
return nil;
}
-(CPLayer *)dataLabelForPlot:(CPPlot *)plot recordIndex:(NSUInteger)index
{
if ( [(NSString *)plot.identifier isEqualToString:barPlot2] )
return (id)[NSNull null]; // Don't show any label
else if ( [(NSString *)plot.identifier isEqualToString:barPlot1] && index < 4 )
return (id)[NSNull null];
else if ( index % 4 ) {
return (id)[NSNull null];
}
else {
return nil; // Use default label style
}
}
#pragma mark -
#pragma mark Plot Space Delegate Methods
-(CPPlotRange *)plotSpace:(CPPlotSpace *)space willChangePlotRangeTo:(CPPlotRange *)newRange forCoordinate:(CPCoordinate)coordinate {
// Impose a limit on how far user can scroll in x
if ( coordinate == CPCoordinateX ) {
CPPlotRange *maxRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-1.0f) length:CPDecimalFromFloat(6.0f)];
CPPlotRange *changedRange = [[newRange copy] autorelease];
[changedRange shiftEndToFitInRange:maxRange];
[changedRange shiftLocationToFitInRange:maxRange];
newRange = changedRange;
}
return newRange;
}
#pragma mark -
#pragma mark CPScatterPlot delegate method
-(void)scatterPlot:(CPScatterPlot *)plot plotSymbolWasSelectedAtRecordIndex:(NSUInteger)index
{
if ( symbolTextAnnotation ) {
[graph.plotAreaFrame.plotArea removeAnnotation:symbolTextAnnotation];
symbolTextAnnotation = nil;
}
// Setup a style for the annotation
CPMutableTextStyle *hitAnnotationTextStyle = [CPMutableTextStyle textStyle];
hitAnnotationTextStyle.color = [CPColor whiteColor];
hitAnnotationTextStyle.fontSize = 16.0f;
hitAnnotationTextStyle.fontName = @"Helvetica-Bold";
// Determine point of symbol in plot coordinates
NSNumber *x = [[self.arrangedObjects objectAtIndex:index] valueForKey:@"x"];
NSNumber *y = [[self.arrangedObjects objectAtIndex:index] valueForKey:@"y"];
NSArray *anchorPoint = [NSArray arrayWithObjects:x, y, nil];
// Add annotation
// First make a string for the y value
NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setMaximumFractionDigits:2];
NSString *yString = [formatter stringFromNumber:y];
// Now add the annotation to the plot area
CPTextLayer *textLayer = [[[CPTextLayer alloc] initWithText:yString style:hitAnnotationTextStyle] autorelease];
symbolTextAnnotation = [[[CPPlotSpaceAnnotation alloc] initWithPlotSpace:graph.defaultPlotSpace anchorPlotPoint:anchorPoint] autorelease];
symbolTextAnnotation.contentLayer = textLayer;
symbolTextAnnotation.displacement = CGPointMake(0.0f, 20.0f);
[graph.plotAreaFrame.plotArea addAnnotation:symbolTextAnnotation];
}
#pragma mark -
#pragma mark CPBarPlot delegate method
-(void)barPlot:(CPBarPlot *)plot barWasSelectedAtRecordIndex:(NSUInteger)index
{
NSLog(@"barWasSelectedAtRecordIndex %lu", index);
if ( symbolTextAnnotation ) {
[graph.plotAreaFrame.plotArea removeAnnotation:symbolTextAnnotation];
symbolTextAnnotation = nil;
}
// Setup a style for the annotation
CPMutableTextStyle *hitAnnotationTextStyle = [CPMutableTextStyle textStyle];
hitAnnotationTextStyle.color = [CPColor redColor];
hitAnnotationTextStyle.fontSize = 16.0f;
hitAnnotationTextStyle.fontName = @"Helvetica-Bold";
// Determine point of symbol in plot coordinates
NSNumber *x = [NSNumber numberWithInt:0];
NSNumber *y = [self numberForPlot:plot field:0 recordIndex:index];
NSArray *anchorPoint = [NSArray arrayWithObjects:x, [NSNumber numberWithInt:index], nil];
// Add annotation
// First make a string for the y value
NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setMaximumFractionDigits:2];
NSString *yString = [formatter stringFromNumber:y];
// Now add the annotation to the plot area
CPTextLayer *textLayer = [[[CPTextLayer alloc] initWithText:yString style:hitAnnotationTextStyle] autorelease];
symbolTextAnnotation = [[[CPPlotSpaceAnnotation alloc] initWithPlotSpace:plot.plotSpace anchorPlotPoint:anchorPoint] autorelease];
symbolTextAnnotation.contentLayer = textLayer;
symbolTextAnnotation.displacement = CGPointMake(0.0f, 0.0f);
[graph.plotAreaFrame.plotArea addAnnotation:symbolTextAnnotation];
}
#pragma mark -
#pragma mark PDF / image export
-(IBAction)exportToPDF:(id)sender
{
NSSavePanel *pdfSavingDialog = [NSSavePanel savePanel];
[pdfSavingDialog setRequiredFileType:@"pdf"];
if ( [pdfSavingDialog runModalForDirectory:nil file:nil] == NSOKButton )
{
NSData *dataForPDF = [graph dataForPDFRepresentationOfLayer];
[dataForPDF writeToFile:[pdfSavingDialog filename] atomically:NO];
}
}
-(IBAction)exportToPNG:(id)sender
{
NSSavePanel *pngSavingDialog = [NSSavePanel savePanel];
[pngSavingDialog setRequiredFileType:@"png"];
if ( [pngSavingDialog runModalForDirectory:nil file:nil] == NSOKButton ) {
NSImage *image = [graph imageOfLayer];
NSData *tiffData = [image TIFFRepresentation];
NSBitmapImageRep *tiffRep = [NSBitmapImageRep imageRepWithData:tiffData];
NSData *pngData = [tiffRep representationUsingType:NSPNGFileType properties:nil];
[pngData writeToFile:[pngSavingDialog filename] atomically:NO];
}
}
#pragma mark -
#pragma mark Layer exploding for illustration
-(IBAction)explodeLayers:(id)sender
{
CATransform3D perspectiveRotation = CATransform3DMakeRotation(-40.0 * M_PI / 180.0, 0.0, 1.0, 0.0);
perspectiveRotation = CATransform3DRotate(perspectiveRotation, -55.0 * M_PI / 180.0, perspectiveRotation.m11, perspectiveRotation.m21, perspectiveRotation.m31);
perspectiveRotation = CATransform3DScale(perspectiveRotation, 0.7, 0.7, 0.7);
graph.masksToBounds = NO;
graph.superlayer.masksToBounds = NO;
overlayRotationView = [(RotationView *)[RotationView alloc] initWithFrame:hostView.frame];
overlayRotationView.rotationDelegate = self;
overlayRotationView.rotationTransform = perspectiveRotation;
[overlayRotationView setAutoresizingMask:[hostView autoresizingMask]];
[[hostView superview] addSubview:overlayRotationView positioned:NSWindowAbove relativeTo:hostView];
[CATransaction begin];
[CATransaction setValue:[NSNumber numberWithFloat:1.0f] forKey:kCATransactionAnimationDuration];
[Controller recursivelySplitSublayersInZForLayer:graph depthLevel:0];
graph.superlayer.sublayerTransform = perspectiveRotation;
[CATransaction commit];
}
+(void)recursivelySplitSublayersInZForLayer:(CALayer *)layer depthLevel:(NSUInteger)depthLevel
{
layer.zPosition = kZDistanceBetweenLayers * (CGFloat)depthLevel;
layer.borderColor = [CPColor blueColor].cgColor;
layer.borderWidth = 2.0;
depthLevel++;
for (CALayer *currentLayer in layer.sublayers) {
[Controller recursivelySplitSublayersInZForLayer:currentLayer depthLevel:depthLevel];
}
}
-(IBAction)reassembleLayers:(id)sender
{
[CATransaction begin];
[CATransaction setValue:[NSNumber numberWithFloat:1.0f] forKey:kCATransactionAnimationDuration];
[Controller recursivelyAssembleSublayersInZForLayer:graph];
graph.superlayer.sublayerTransform = CATransform3DIdentity;
[CATransaction commit];
[overlayRotationView removeFromSuperview];
[overlayRotationView release];
overlayRotationView = nil;
}
+(void)recursivelyAssembleSublayersInZForLayer:(CALayer *)layer
{
layer.zPosition = 0.0;
layer.borderColor = [CPColor clearColor].cgColor;
layer.borderWidth = 0.0;
for (CALayer *currentLayer in layer.sublayers) {
[Controller recursivelyAssembleSublayersInZForLayer:currentLayer];
}
}
#pragma mark -
#pragma mark Demo windows
-(IBAction)plotSymbolDemo:(id)sender
{
if ( !plotSymbolWindow ) {
[NSBundle loadNibNamed:@"PlotSymbolDemo" owner:self];
}
[plotSymbolWindow makeKeyAndOrderFront:sender];
}
-(IBAction)axisDemo:(id)sender
{
if ( !axisDemoWindow ) {
[NSBundle loadNibNamed:@"AxisDemo" owner:self];
}
[axisDemoWindow makeKeyAndOrderFront:sender];
}
-(IBAction)selectionDemo:(id)sender
{
if ( !selectionDemoWindow ) {
[NSBundle loadNibNamed:@"SelectionDemo" owner:self];
}
[axisDemoWindow makeKeyAndOrderFront:sender];
}
#pragma mark -
#pragma mark CPRotationDelegate delegate method
-(void)rotateObjectUsingTransform:(CATransform3D)rotationTransform
{
[CATransaction begin];
[CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
graph.superlayer.sublayerTransform = rotationTransform;
[CATransaction commit];
}
#pragma mark -
#pragma mark Accessors
-(void)setXShift:(CGFloat)newShift
{
xShift = newShift;
CPXYPlotSpace *space = (CPXYPlotSpace *)graph.defaultPlotSpace;
CPPlotRange *newRange = [[space.xRange copy] autorelease];
newRange.length = CPDecimalFromDouble(3.0 + newShift);
space.xRange = newRange;
}
-(void)setYShift:(CGFloat)newShift
{
yShift = newShift;
CPXYPlotSpace *space = (CPXYPlotSpace *)graph.defaultPlotSpace;
CPPlotRange *newRange = [[space.yRange copy] autorelease];
newRange.length = CPDecimalFromDouble(2.0 + newShift);
space.yRange = newRange;
}
-(void)setLabelRotation:(CGFloat)newRotation
{
labelRotation = newRotation;
((CPXYAxisSet *)graph.axisSet).yAxis.labelRotation = newRotation;
[graph plotWithIdentifier:dataSourcePlot].labelRotation = newRotation;
}
@end
| 08iteng-ipad | examples/CPTestApp/Source/Controller.m | Objective-C | bsd | 23,560 |
#import "CPPlotSymbolTestController.h"
@implementation CPPlotSymbolTestController
-(void)dealloc
{
[graph release];
[super dealloc];
}
-(void)awakeFromNib
{
[super awakeFromNib];
// Create graph
graph = [(CPXYGraph *)[CPXYGraph alloc] initWithFrame:NSRectToCGRect(hostView.bounds)];
hostView.hostedLayer = graph;
// Remove axes
graph.axisSet = nil;
// Background
CGColorRef grayColor = CGColorCreateGenericGray(0.7, 1.0);
graph.fill = [CPFill fillWithColor:[CPColor colorWithCGColor:grayColor]];
CGColorRelease(grayColor);
// Plot area
grayColor = CGColorCreateGenericGray(0.2, 0.3);
graph.plotAreaFrame.fill = [CPFill fillWithColor:[CPColor colorWithCGColor:grayColor]];
CGColorRelease(grayColor);
// Setup plot space
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-1.0) length:CPDecimalFromFloat(11.0)];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-1.0) length:CPDecimalFromFloat(14.0)];
// Create a series of plots that uses the data source method
for (NSUInteger i = CPPlotSymbolTypeNone; i <= CPPlotSymbolTypeCustom; i++) {
CPScatterPlot *dataSourceLinePlot = [[(CPScatterPlot *)[CPScatterPlot alloc] initWithFrame:graph.bounds] autorelease];
dataSourceLinePlot.identifier = [NSString stringWithFormat:@"%lu", (unsigned long)i];
CPMutableLineStyle *lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.lineWidth = 1.f;
lineStyle.lineColor = [CPColor redColor];
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.dataSource = self;
[graph addPlot:dataSourceLinePlot];
}
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
return 10;
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSDecimalNumber *num;
switch (fieldEnum) {
case CPScatterPlotFieldX:
num = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%ud", index]];
break;
case CPScatterPlotFieldY:
num = [NSDecimalNumber decimalNumberWithString:(NSString *)plot.identifier];
break;
default:
num = [NSDecimalNumber zero];
};
return num;
}
-(CPPlotSymbol *)symbolForScatterPlot:(CPScatterPlot *)plot recordIndex:(NSUInteger)index
{
CPGradient *gradientFill = [CPGradient rainbowGradient];
gradientFill.gradientType = CPGradientTypeRadial;
gradientFill.angle = 90;
CPPlotSymbol *symbol = [[[CPPlotSymbol alloc] init] autorelease];
symbol.symbolType = [(NSString *)plot.identifier intValue];
symbol.fill = [CPFill fillWithGradient:gradientFill];
if (index > 0) {
symbol.size = CGSizeMake(index * 4, index * 4);
}
if (symbol.symbolType == CPPlotSymbolTypeCustom) {
// Creating the custom path.
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 0., 0.);
CGPathAddEllipseInRect(path, NULL, CGRectMake(0., 0., 10., 10.));
CGPathAddEllipseInRect(path, NULL, CGRectMake(1.5, 4., 3., 3.));
CGPathAddEllipseInRect(path, NULL, CGRectMake(5.5, 4., 3., 3.));
CGPathMoveToPoint(path, NULL, 5., 2.);
CGPathAddArc(path, NULL, 5., 3.3, 2.8, 0., pi, TRUE);
CGPathCloseSubpath(path);
symbol.customSymbolPath = path;
symbol.usesEvenOddClipRule = YES;
CGPathRelease(path);
}
return symbol;
}
@end
| 08iteng-ipad | examples/CPTestApp/Source/CPPlotSymbolTestController.m | Objective-C | bsd | 3,481 |
//
// main.m
// CPTestApp
//
// Created by Dirkjan Krijnders on 2/2/09.
// Copyright __MyCompanyName__ 2009. All rights reserved.
//
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **) argv);
}
| 08iteng-ipad | examples/CPTestApp/Source/main.m | Objective-C | bsd | 259 |
//
// RotationView.h
// CPTestApp
//
#import <Cocoa/Cocoa.h>
#import <QuartzCore/QuartzCore.h>
@protocol CPRotationDelegate;
@interface RotationView : NSView {
id<CPRotationDelegate> rotationDelegate;
CATransform3D rotationTransform;
NSPoint previousLocation;
}
@property(readwrite, nonatomic) CATransform3D rotationTransform;
@property(readwrite, assign, nonatomic) id<CPRotationDelegate> rotationDelegate;
@end
@protocol CPRotationDelegate <NSObject>
- (void)rotateObjectUsingTransform:(CATransform3D)rotationTransform;
@end
| 08iteng-ipad | examples/CPTestApp/Source/RotationView.h | Objective-C | bsd | 542 |
#import <Cocoa/Cocoa.h>
#import <CorePlot/CorePlot.h>
@interface CPPlotSymbolTestController : NSObject <CPScatterPlotDataSource> {
IBOutlet CPLayerHostingView *hostView;
CPXYGraph *graph;
}
@end
| 08iteng-ipad | examples/CPTestApp/Source/CPPlotSymbolTestController.h | Objective-C | bsd | 203 |
#import "SelectionDemoController.h"
static NSString * const MAIN_PLOT = @"Scatter Plot";
static NSString * const SELECTION_PLOT = @"Selection Plot";
@interface SelectionDemoController()
-(void)setupGraph;
-(void)setupAxes;
-(void)setupScatterPlots;
-(void)initializeData;
@property (nonatomic, readwrite, retain) NSMutableArray *dataForPlot;
@property (nonatomic, readwrite) NSUInteger selectedIndex;
@end
#pragma mark -
@implementation SelectionDemoController
@synthesize dataForPlot;
@synthesize selectedIndex;
-(void)dealloc
{
[graph release];
[dataForPlot release];
[super dealloc];
}
-(void)awakeFromNib
{
[super awakeFromNib];
selectedIndex = NSUIntegerMax;
[self initializeData];
[self setupGraph];
[self setupAxes];
[self setupScatterPlots];
}
#pragma mark -
#pragma mark Graph Setup Methods
-(void)setupGraph
{
// Create graph and apply a dark theme
graph = [(CPXYGraph *)[CPXYGraph alloc] initWithFrame:NSRectToCGRect(hostView.bounds)];
CPTheme *theme = [CPTheme themeNamed:kCPSlateTheme];
[graph applyTheme:theme];
hostView.hostedLayer = graph;
// Graph title
graph.title = @"This is the Graph Title";
CPMutableTextStyle *textStyle = [CPMutableTextStyle textStyle];
textStyle.color = [CPColor grayColor];
textStyle.fontName = @"Helvetica-Bold";
textStyle.fontSize = 18.0;
graph.titleTextStyle = textStyle;
graph.titleDisplacement = CGPointMake(0.0, 10.0);
graph.titlePlotAreaFrameAnchor = CPRectAnchorTop;
// Graph padding
graph.paddingLeft = 20.0;
graph.paddingTop = 20.0;
graph.paddingRight = 20.0;
graph.paddingBottom = 20.0;
}
-(void)setupAxes
{
// Setup scatter plot space
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
#ifdef REMOVE_SELECTION_ON_CLICK
plotSpace.delegate = self;
#endif
// Grid line styles
CPMutableLineStyle *majorGridLineStyle = [CPMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [[CPColor colorWithGenericGray:0.2] colorWithAlphaComponent:0.75];
CPMutableLineStyle *minorGridLineStyle = [CPMutableLineStyle lineStyle];
minorGridLineStyle.lineWidth = 0.25;
minorGridLineStyle.lineColor = [[CPColor whiteColor] colorWithAlphaComponent:0.1];
// Axes
// Label x axis with a fixed interval policy
CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.labelingPolicy = CPAxisLabelingPolicyAutomatic;
x.minorTicksPerInterval = 4;
x.preferredNumberOfMajorTicks = 8;
x.majorGridLineStyle = majorGridLineStyle;
x.minorGridLineStyle = minorGridLineStyle;
x.title = @"X Axis";
x.titleOffset = 30.0;
// Label y with an automatic label policy.
CPXYAxis *y = axisSet.yAxis;
y.labelingPolicy = CPAxisLabelingPolicyAutomatic;
y.minorTicksPerInterval = 4;
y.preferredNumberOfMajorTicks = 8;
y.majorGridLineStyle = majorGridLineStyle;
y.minorGridLineStyle = minorGridLineStyle;
y.labelOffset = 10.0;
y.title = @"Y Axis";
y.titleOffset = 30.0;
}
-(void)setupScatterPlots
{
// Create a plot that uses the data source method
CPScatterPlot *dataSourceLinePlot = [[[CPScatterPlot alloc] init] autorelease];
dataSourceLinePlot.identifier = MAIN_PLOT;
dataSourceLinePlot.cachePrecision = CPPlotCachePrecisionDouble;
CPMutableLineStyle *lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.lineWidth = 2.0;
lineStyle.lineColor = [CPColor greenColor];
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.dataSource = self;
[graph addPlot:dataSourceLinePlot];
// Set plot delegate, to know when symbols have been touched
// We will display an annotation when a symbol is touched
dataSourceLinePlot.delegate = self;
dataSourceLinePlot.plotSymbolMarginForHitDetection = 5.0;
// Create a plot for the selection marker
CPScatterPlot *selectionPlot = [[[CPScatterPlot alloc] init] autorelease];
selectionPlot.identifier = SELECTION_PLOT;
selectionPlot.cachePrecision = CPPlotCachePrecisionDouble;
lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.lineWidth = 3.0;
lineStyle.lineColor = [CPColor redColor];
selectionPlot.dataLineStyle = lineStyle;
selectionPlot.dataSource = self;
[graph addPlot:selectionPlot];
// Auto scale the plot space to fit the plot data
// Compress ranges so we can scroll
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
[plotSpace scaleToFitPlots:[NSArray arrayWithObject:dataSourceLinePlot]];
CPPlotRange *xRange = plotSpace.xRange;
[xRange expandRangeByFactor:CPDecimalFromDouble(0.75)];
plotSpace.xRange = xRange;
CPPlotRange *yRange = plotSpace.yRange;
[yRange expandRangeByFactor:CPDecimalFromDouble(0.75)];
plotSpace.yRange = yRange;
CPPlotRange *globalXRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(-1.0) length:CPDecimalFromDouble(10.0)];
plotSpace.globalXRange = globalXRange;
CPPlotRange *globalYRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(-5.0) length:CPDecimalFromDouble(10.0)];
plotSpace.globalYRange = globalYRange;
}
-(void)initializeData
{
NSMutableArray *contentArray = [NSMutableArray arrayWithCapacity:100];
for ( NSUInteger i = 0; i < 100; i++ ) {
id x = [NSNumber numberWithDouble:i * 0.05];
id y = [NSNumber numberWithDouble:10.0 * rand()/(double)RAND_MAX - 5.0];
[contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x, @"x", y, @"y", nil]];
}
self.dataForPlot = contentArray;
}
#pragma mark -
#pragma mark Plot datasource methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
NSUInteger count = 0;
if ( [(NSString *)plot.identifier isEqualToString:MAIN_PLOT] ) {
count = [self.dataForPlot count];
}
else if ( [(NSString *)plot.identifier isEqualToString:SELECTION_PLOT] ) {
if ( self.selectedIndex < NSUIntegerMax ) {
count = 5;
}
}
return count;
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSNumber *num = nil;
if ( [(NSString *)plot.identifier isEqualToString:MAIN_PLOT] ) {
num = [[self.dataForPlot objectAtIndex:index] valueForKey:(fieldEnum == CPScatterPlotFieldX ? @"x" : @"y")];
}
else if ( [(NSString *)plot.identifier isEqualToString:SELECTION_PLOT] ) {
CPXYPlotSpace *thePlotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
switch ( fieldEnum ) {
case CPScatterPlotFieldX:
switch ( index ) {
case 0:
num = [NSDecimalNumber decimalNumberWithDecimal:thePlotSpace.globalXRange.minLimit];
break;
case 1:
num = [NSDecimalNumber decimalNumberWithDecimal:thePlotSpace.globalXRange.maxLimit];
break;
case 2:
case 3:
case 4:
num = [[self.dataForPlot objectAtIndex:self.selectedIndex] valueForKey:@"x"];
break;
default:
break;
}
break;
case CPScatterPlotFieldY:
switch ( index ) {
case 0:
case 1:
case 2:
num = [[self.dataForPlot objectAtIndex:self.selectedIndex] valueForKey:@"y"];
break;
case 3:
num = [NSDecimalNumber decimalNumberWithDecimal:thePlotSpace.globalYRange.maxLimit];
break;
case 4:
num = [NSDecimalNumber decimalNumberWithDecimal:thePlotSpace.globalYRange.minLimit];
break;
default:
break;
}
break;
default:
break;
}
}
return num;
}
-(CPPlotSymbol *)symbolForScatterPlot:(CPScatterPlot *)plot recordIndex:(NSUInteger)index
{
static CPPlotSymbol *redDot = nil;
CPPlotSymbol *symbol = (id)[NSNull null];
if ( [(NSString *)plot.identifier isEqualToString:SELECTION_PLOT] && (index == 2) ) {
if ( !redDot ) {
redDot = [[CPPlotSymbol alloc] init];
redDot.symbolType = CPPlotSymbolTypeEllipse;
redDot.size = CGSizeMake(10.0, 10.0);
redDot.fill = [CPFill fillWithColor:[CPColor redColor]];
}
symbol = redDot;
}
return symbol;
}
#pragma mark -
#pragma mark CPScatterPlot delegate methods
-(void)scatterPlot:(CPScatterPlot *)plot plotSymbolWasSelectedAtRecordIndex:(NSUInteger)index
{
self.selectedIndex = index;
}
#pragma mark -
#pragma mark Plot space delegate methods
#ifdef REMOVE_SELECTION_ON_CLICK
-(BOOL)plotSpace:(CPPlotSpace *)space shouldHandlePointingDeviceDownEvent:(id)event atPoint:(CGPoint)point
{
self.selectedIndex = NSUIntegerMax;
return YES;
}
#endif
#pragma mark -
#pragma mark Accesors
-(void)setSelectedIndex:(NSUInteger)newIndex
{
if ( selectedIndex != newIndex ) {
selectedIndex = newIndex;
[[graph plotWithIdentifier:SELECTION_PLOT] reloadData];
}
}
@end
| 08iteng-ipad | examples/CPTestApp/Source/SelectionDemoController.m | Objective-C | bsd | 8,833 |
//
// 3DRotationView.m
// CPTestApp
//
#import "RotationView.h"
static const CGFloat kMouseMovementScaleFactorForRotation = 1.0f;
@implementation RotationView
#pragma mark -
#pragma mark Initialization and teardown
- (id)initWithFrame:(NSRect)frame
{
if ( self = [super initWithFrame:frame] ) {
rotationTransform = CATransform3DIdentity;
// Initialization code here.
}
return self;
}
#pragma mark -
#pragma mark Mouse handling methods
- (BOOL)acceptsFirstMouse:(NSEvent *)theEvent
{
return YES;
}
- (void)mouseDown:(NSEvent *)theEvent
{
previousLocation = [self convertPoint:[theEvent locationInWindow] fromView:nil];
}
- (void)mouseDragged:(NSEvent *)theEvent
{
NSPoint currentLocation = [self convertPoint:[theEvent locationInWindow] fromView:nil];
CGFloat displacementInX = kMouseMovementScaleFactorForRotation * (currentLocation.x - previousLocation.x);
CGFloat displacementInY = kMouseMovementScaleFactorForRotation * (previousLocation.y - currentLocation.y);
CGFloat totalRotation = sqrt(displacementInX * displacementInX + displacementInY * displacementInY);
rotationTransform = CATransform3DRotate(rotationTransform, totalRotation * M_PI / 180.0,
((displacementInX/totalRotation) * rotationTransform.m12 + (displacementInY/totalRotation) * rotationTransform.m11),
((displacementInX/totalRotation) * rotationTransform.m22 + (displacementInY/totalRotation) * rotationTransform.m21),
((displacementInX/totalRotation) * rotationTransform.m32 + (displacementInY/totalRotation) * rotationTransform.m31));
[rotationDelegate rotateObjectUsingTransform:rotationTransform];
previousLocation = [self convertPoint:[theEvent locationInWindow] fromView:nil];
}
- (void)mouseUp:(NSEvent *)theEvent
{
previousLocation = [self convertPoint:[theEvent locationInWindow] fromView:nil];
}
#pragma mark -
#pragma mark Accessors
@synthesize rotationTransform;
@synthesize rotationDelegate;
@end
| 08iteng-ipad | examples/CPTestApp/Source/RotationView.m | Objective-C | bsd | 1,982 |
#import <Cocoa/Cocoa.h>
#import <CorePlot/CorePlot.h>
#import "RotationView.h"
@interface Controller : NSArrayController <CPPlotDataSource, CPRotationDelegate, CPPlotSpaceDelegate, CPBarPlotDelegate> {
IBOutlet CPLayerHostingView *hostView;
IBOutlet NSWindow *plotSymbolWindow;
IBOutlet NSWindow *axisDemoWindow;
IBOutlet NSWindow *selectionDemoWindow;
CPXYGraph *graph;
RotationView *overlayRotationView;
CPLayerAnnotation *symbolTextAnnotation;
CGFloat xShift;
CGFloat yShift;
CGFloat labelRotation;
}
@property (nonatomic) CGFloat xShift;
@property (nonatomic) CGFloat yShift;
@property (nonatomic) CGFloat labelRotation;
// Data loading
-(IBAction)reloadDataSourcePlot:(id)sender;
-(IBAction)removeData:(id)sender;
-(IBAction)insertData:(id)sender;
// PDF / image export
-(IBAction)exportToPDF:(id)sender;
-(IBAction)exportToPNG:(id)sender;
// Layer exploding for illustration
-(IBAction)explodeLayers:(id)sender;
+(void)recursivelySplitSublayersInZForLayer:(CALayer *)layer depthLevel:(NSUInteger)depthLevel;
-(IBAction)reassembleLayers:(id)sender;
+(void)recursivelyAssembleSublayersInZForLayer:(CALayer *)layer;
// Demo windows
-(IBAction)plotSymbolDemo:(id)sender;
-(IBAction)axisDemo:(id)sender;
-(IBAction)selectionDemo:(id)sender;
@end
| 08iteng-ipad | examples/CPTestApp/Source/Controller.h | Objective-C | bsd | 1,289 |
#import "AxisDemoController.h"
@implementation AxisDemoController
-(void)awakeFromNib
{
[super awakeFromNib];
// Background
CPBorderedLayer *background = [[(CPBorderedLayer *)[CPBorderedLayer alloc] initWithFrame:NSRectToCGRect(hostView.bounds)] autorelease];
background.fill = [CPFill fillWithColor:[CPColor blueColor]];
background.paddingTop = 20.0;
background.paddingBottom = 20.0;
background.paddingLeft = 20.0;
background.paddingRight = 20.0;
hostView.hostedLayer = background;
// Create graph
CPXYGraph *graph = [[(CPXYGraph *)[CPXYGraph alloc] initWithFrame:background.bounds] autorelease];
graph.fill = [CPFill fillWithColor:[CPColor darkGrayColor]];
graph.cornerRadius = 20.0;
[background addSublayer:graph];
// Plot area
graph.plotAreaFrame.fill = [CPFill fillWithColor:[CPColor lightGrayColor]];
graph.plotAreaFrame.paddingTop = 20.0;
graph.plotAreaFrame.paddingBottom = 50.0;
graph.plotAreaFrame.paddingLeft = 50.0;
graph.plotAreaFrame.paddingRight = 20.0;
graph.plotAreaFrame.cornerRadius = 10.0;
graph.plotAreaFrame.axisSet.borderLineStyle = [CPLineStyle lineStyle];
graph.plotAreaFrame.plotArea.fill = [CPFill fillWithColor:[CPColor whiteColor]];
// Setup plot space
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(-10.0)];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.5) length:CPDecimalFromDouble(10.0)];
// Line styles
CPMutableLineStyle *axisLineStyle = [CPMutableLineStyle lineStyle];
axisLineStyle.lineWidth = 3.0;
axisLineStyle.lineCap = kCGLineCapRound;
CPMutableLineStyle *majorGridLineStyle = [CPMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [CPColor redColor];
CPMutableLineStyle *minorGridLineStyle = [CPMutableLineStyle lineStyle];
minorGridLineStyle.lineWidth = 0.25;
minorGridLineStyle.lineColor = [CPColor blueColor];
// Text styles
CPMutableTextStyle *axisTitleTextStyle = [CPMutableTextStyle textStyle];
axisTitleTextStyle.fontName = @"Helvetica Bold";
axisTitleTextStyle.fontSize = 14.0;
// Axes
// Label x axis with a fixed interval policy
CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.separateLayers = NO;
x.orthogonalCoordinateDecimal = CPDecimalFromDouble(0.5);
x.majorIntervalLength = CPDecimalFromString(@"0.5");
x.minorTicksPerInterval = 4;
x.tickDirection = CPSignNone;
x.axisLineStyle = axisLineStyle;
x.majorTickLength = 12.0;
x.majorTickLineStyle = axisLineStyle;
x.majorGridLineStyle = majorGridLineStyle;
x.minorTickLength = 8.0;
x.minorGridLineStyle = minorGridLineStyle;
x.title = @"X Axis";
x.titleTextStyle = axisTitleTextStyle;
x.titleOffset = 25.0;
x.alternatingBandFills = [NSArray arrayWithObjects:[[CPColor redColor] colorWithAlphaComponent:0.1], [[CPColor greenColor] colorWithAlphaComponent:0.1], nil];
// Label y with an automatic label policy.
axisLineStyle.lineColor = [CPColor greenColor];
CPXYAxis *y = axisSet.yAxis;
y.separateLayers = YES;
y.minorTicksPerInterval = 9;
y.tickDirection = CPSignNone;
y.axisLineStyle = axisLineStyle;
y.majorTickLength = 12.0;
y.majorTickLineStyle = axisLineStyle;
y.majorGridLineStyle = majorGridLineStyle;
y.minorTickLength = 8.0;
y.minorGridLineStyle = minorGridLineStyle;
y.title = @"Y Axis";
y.titleTextStyle = axisTitleTextStyle;
y.titleOffset = 30.0;
y.alternatingBandFills = [NSArray arrayWithObjects:[[CPColor blueColor] colorWithAlphaComponent:0.1], [NSNull null], nil];
CPFill *bandFill = [CPFill fillWithColor:[[CPColor darkGrayColor] colorWithAlphaComponent:0.5]];
[y addBackgroundLimitBand:[CPLimitBand limitBandWithRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(7.0) length:CPDecimalFromDouble(1.5)] fill:bandFill]];
[y addBackgroundLimitBand:[CPLimitBand limitBandWithRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(1.5) length:CPDecimalFromDouble(3.0)] fill:bandFill]];
}
@end
| 08iteng-ipad | examples/CPTestApp/Source/AxisDemoController.m | Objective-C | bsd | 4,158 |
#import <Cocoa/Cocoa.h>
#import <CorePlot/CorePlot.h>
@interface SelectionDemoController : NSObject <CPScatterPlotDataSource, CPPlotSpaceDelegate> {
IBOutlet CPLayerHostingView *hostView;
CPXYGraph *graph;
NSMutableArray *dataForPlot;
NSUInteger selectedIndex;
}
@end
| 08iteng-ipad | examples/CPTestApp/Source/SelectionDemoController.h | Objective-C | bsd | 277 |
//
// main.m
// CPTestApp-iPhone
//
// Created by Brad Larson on 5/11/2009.
//
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
| 08iteng-ipad | examples/CPTestApp-iPhone/main.m | Objective-C | bsd | 308 |
#import <UIKit/UIKit.h>
#import "CorePlot-CocoaTouch.h"
@interface CPTestAppPieChartController : UIViewController <CPPieChartDataSource, CPPieChartDelegate>
{
@private
CPXYGraph *pieChart;
NSMutableArray *dataForChart;
NSTimer *timer;
}
@property(readwrite, retain, nonatomic) NSMutableArray *dataForChart;
@property(readwrite, retain, nonatomic) NSTimer *timer;
-(void)timerFired;
@end
| 08iteng-ipad | examples/CPTestApp-iPhone/Classes/CPTestAppPieChartController.h | Objective-C | bsd | 396 |
//
// CPTestAppBarChartController.h
// CPTestApp-iPhone
//
#import <UIKit/UIKit.h>
#import "CorePlot-CocoaTouch.h"
@interface CPTestAppBarChartController : UIViewController <CPPlotDataSource>
{
@private
CPXYGraph *barChart;
NSTimer *timer;
}
@property(readwrite, retain, nonatomic) NSTimer *timer;
-(void)timerFired;
@end
| 08iteng-ipad | examples/CPTestApp-iPhone/Classes/CPTestAppBarChartController.h | Objective-C | bsd | 331 |
//
// CPTestApp_iPhoneAppDelegate.m
// CPTestApp-iPhone
//
// Created by Brad Larson on 5/11/2009.
#import "CPTestApp_iPhoneAppDelegate.h"
@implementation CPTestApp_iPhoneAppDelegate
@synthesize window;
@synthesize tabBarController;
-(void)applicationDidFinishLaunching:(UIApplication *)application {
// Add the tab bar controller's current view as a subview of the window
[window addSubview:tabBarController.view];
}
/*
// Optional UITabBarControllerDelegate method
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
}
*/
/*
// Optional UITabBarControllerDelegate method
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed {
}
*/
-(void)dealloc {
[tabBarController release];
[window release];
[super dealloc];
}
@end
| 08iteng-ipad | examples/CPTestApp-iPhone/Classes/CPTestApp_iPhoneAppDelegate.m | Objective-C | bsd | 926 |
#import "CPTestAppPieChartController.h"
@implementation CPTestAppPieChartController
@synthesize dataForChart;
@synthesize timer;
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
return YES;
}
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
CGFloat margin = pieChart.plotAreaFrame.borderLineStyle.lineWidth + 5.0;
CPPlot *piePlot = [pieChart plotWithIdentifier:@"Pie Chart 1"];
CGRect plotBounds = pieChart.plotAreaFrame.bounds;
CGFloat newRadius = MIN(plotBounds.size.width, plotBounds.size.height) / 2.0 - margin;
((CPPieChart *)piePlot).pieRadius = newRadius;
CGFloat y = 0.0;
if ( plotBounds.size.width > plotBounds.size.height ) {
y = 0.5;
}
else {
y = (newRadius + margin) / plotBounds.size.height;
}
((CPPieChart *)piePlot).centerAnchor = CGPointMake(0.5, y);
}
#pragma mark -
#pragma mark Initialization and teardown
-(void)dealloc
{
[dataForChart release];
[timer release];
[super dealloc];
}
-(void)viewDidAppear:(BOOL)animated
{
// Add some initial data
NSMutableArray *contentArray = [NSMutableArray arrayWithObjects:[NSNumber numberWithDouble:20.0], [NSNumber numberWithDouble:30.0], [NSNumber numberWithDouble:60.0], nil];
self.dataForChart = contentArray;
[self timerFired];
#ifdef MEMORY_TEST
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self
selector:@selector(timerFired) userInfo:nil repeats:YES];
#endif
}
-(void)timerFired
{
#ifdef MEMORY_TEST
static NSUInteger counter = 0;
NSLog(@"\n----------------------------\ntimerFired: %lu", counter++);
#endif
[pieChart release];
// Create pieChart from theme
pieChart = [[CPXYGraph alloc] initWithFrame:CGRectZero];
CPTheme *theme = [CPTheme themeNamed:kCPDarkGradientTheme];
[pieChart applyTheme:theme];
CPGraphHostingView *hostingView = (CPGraphHostingView *)self.view;
hostingView.hostedGraph = pieChart;
pieChart.paddingLeft = 20.0;
pieChart.paddingTop = 20.0;
pieChart.paddingRight = 20.0;
pieChart.paddingBottom = 20.0;
pieChart.axisSet = nil;
pieChart.titleTextStyle.color = [CPColor whiteColor];
pieChart.title = @"Graph Title";
// Add pie chart
CPPieChart *piePlot = [[CPPieChart alloc] init];
piePlot.dataSource = self;
piePlot.pieRadius = 131.0;
piePlot.identifier = @"Pie Chart 1";
piePlot.startAngle = M_PI_4;
piePlot.sliceDirection = CPPieDirectionCounterClockwise;
piePlot.centerAnchor = CGPointMake(0.5, 0.38);
piePlot.borderLineStyle = [CPLineStyle lineStyle];
piePlot.delegate = self;
[pieChart addPlot:piePlot];
[piePlot release];
#ifdef PERFORMANCE_TEST
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(changePlotRange) userInfo:nil repeats:YES];
#endif
}
-(void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
return [self.dataForChart count];
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
if ( index >= [self.dataForChart count] ) return nil;
if ( fieldEnum == CPPieChartFieldSliceWidth ) {
return [self.dataForChart objectAtIndex:index];
}
else {
return [NSNumber numberWithInt:index];
}
}
-(CPLayer *)dataLabelForPlot:(CPPlot *)plot recordIndex:(NSUInteger)index
{
CPTextLayer *label = [[CPTextLayer alloc] initWithText:[NSString stringWithFormat:@"%lu", index]];
CPMutableTextStyle *textStyle = [label.textStyle mutableCopy];
textStyle.color = [CPColor lightGrayColor];
label.textStyle = textStyle;
[textStyle release];
return [label autorelease];
}
-(CGFloat)radialOffsetForPieChart:(CPPieChart *)pieChart recordIndex:(NSUInteger)index
{
return ( index == 0 ? 30.0f : 0.0f );
}
/*-(CPFill *)sliceFillForPieChart:(CPPieChart *)pieChart recordIndex:(NSUInteger)index;
{
return nil;
}*/
#pragma mark -
#pragma mark Delegate Methods
-(void)pieChart:(CPPieChart *)plot sliceWasSelectedAtRecordIndex:(NSUInteger)index
{
pieChart.title = [NSString stringWithFormat:@"Selected index: %lu", index];
}
@end
| 08iteng-ipad | examples/CPTestApp-iPhone/Classes/CPTestAppPieChartController.m | Objective-C | bsd | 4,307 |
//
// CPTestApp_iPhoneAppDelegate.h
// CPTestApp-iPhone
//
// Toolbar icons in the application are courtesy of Joseph Wain / glyphish.com
// See the license file in the GlyphishIcons directory for more information on these icons
#import <UIKit/UIKit.h>
@interface CPTestApp_iPhoneAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate> {
UIWindow *window;
UITabBarController *tabBarController;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UITabBarController *tabBarController;
@end
| 08iteng-ipad | examples/CPTestApp-iPhone/Classes/CPTestApp_iPhoneAppDelegate.h | Objective-C | bsd | 570 |
//
// CPTestAppScatterPlotController.m
// CPTestApp-iPhone
//
// Created by Brad Larson on 5/11/2009.
//
#import "CPTestAppScatterPlotController.h"
@implementation CPTestAppScatterPlotController
@synthesize dataForPlot;
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
return YES;
}
#pragma mark -
#pragma mark Initialization and teardown
-(void)dealloc
{
[dataForPlot release];
[super dealloc];
}
-(void)viewDidLoad
{
[super viewDidLoad];
// Create graph from theme
graph = [[CPXYGraph alloc] initWithFrame:CGRectZero];
CPTheme *theme = [CPTheme themeNamed:kCPDarkGradientTheme];
[graph applyTheme:theme];
CPGraphHostingView *hostingView = (CPGraphHostingView *)self.view;
hostingView.collapsesLayers = NO; // Setting to YES reduces GPU memory usage, but can slow drawing/scrolling
hostingView.hostedGraph = graph;
graph.paddingLeft = 10.0;
graph.paddingTop = 10.0;
graph.paddingRight = 10.0;
graph.paddingBottom = 10.0;
// Setup plot space
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(1.0) length:CPDecimalFromFloat(2.0)];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(1.0) length:CPDecimalFromFloat(3.0)];
// Axes
CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.majorIntervalLength = CPDecimalFromString(@"0.5");
x.orthogonalCoordinateDecimal = CPDecimalFromString(@"2");
x.minorTicksPerInterval = 2;
NSArray *exclusionRanges = [NSArray arrayWithObjects:
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(1.99) length:CPDecimalFromFloat(0.02)],
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.99) length:CPDecimalFromFloat(0.02)],
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(2.99) length:CPDecimalFromFloat(0.02)],
nil];
x.labelExclusionRanges = exclusionRanges;
CPXYAxis *y = axisSet.yAxis;
y.majorIntervalLength = CPDecimalFromString(@"0.5");
y.minorTicksPerInterval = 5;
y.orthogonalCoordinateDecimal = CPDecimalFromString(@"2");
exclusionRanges = [NSArray arrayWithObjects:
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(1.99) length:CPDecimalFromFloat(0.02)],
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.99) length:CPDecimalFromFloat(0.02)],
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(3.99) length:CPDecimalFromFloat(0.02)],
nil];
y.labelExclusionRanges = exclusionRanges;
// Create a blue plot area
CPScatterPlot *boundLinePlot = [[[CPScatterPlot alloc] init] autorelease];
CPMutableLineStyle *lineStyle = [CPMutableLineStyle lineStyle];
lineStyle.miterLimit = 1.0f;
lineStyle.lineWidth = 3.0f;
lineStyle.lineColor = [CPColor blueColor];
boundLinePlot.dataLineStyle = lineStyle;
boundLinePlot.identifier = @"Blue Plot";
boundLinePlot.dataSource = self;
[graph addPlot:boundLinePlot];
// Do a blue gradient
CPColor *areaColor1 = [CPColor colorWithComponentRed:0.3 green:0.3 blue:1.0 alpha:0.8];
CPGradient *areaGradient1 = [CPGradient gradientWithBeginningColor:areaColor1 endingColor:[CPColor clearColor]];
areaGradient1.angle = -90.0f;
CPFill *areaGradientFill = [CPFill fillWithGradient:areaGradient1];
boundLinePlot.areaFill = areaGradientFill;
boundLinePlot.areaBaseValue = [[NSDecimalNumber zero] decimalValue];
// Add plot symbols
CPMutableLineStyle *symbolLineStyle = [CPMutableLineStyle lineStyle];
symbolLineStyle.lineColor = [CPColor blackColor];
CPPlotSymbol *plotSymbol = [CPPlotSymbol ellipsePlotSymbol];
plotSymbol.fill = [CPFill fillWithColor:[CPColor blueColor]];
plotSymbol.lineStyle = symbolLineStyle;
plotSymbol.size = CGSizeMake(10.0, 10.0);
boundLinePlot.plotSymbol = plotSymbol;
// Create a green plot area
CPScatterPlot *dataSourceLinePlot = [[[CPScatterPlot alloc] init] autorelease];
lineStyle = [CPMutableLineStyle lineStyle];
lineStyle.lineWidth = 3.f;
lineStyle.lineColor = [CPColor greenColor];
lineStyle.dashPattern = [NSArray arrayWithObjects:[NSNumber numberWithFloat:5.0f], [NSNumber numberWithFloat:5.0f], nil];
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.identifier = @"Green Plot";
dataSourceLinePlot.dataSource = self;
// Put an area gradient under the plot above
CPColor *areaColor = [CPColor colorWithComponentRed:0.3 green:1.0 blue:0.3 alpha:0.8];
CPGradient *areaGradient = [CPGradient gradientWithBeginningColor:areaColor endingColor:[CPColor clearColor]];
areaGradient.angle = -90.0f;
areaGradientFill = [CPFill fillWithGradient:areaGradient];
dataSourceLinePlot.areaFill = areaGradientFill;
dataSourceLinePlot.areaBaseValue = CPDecimalFromString(@"1.75");
// Animate in the new plot, as an example
dataSourceLinePlot.opacity = 0.0f;
[graph addPlot:dataSourceLinePlot];
CABasicAnimation *fadeInAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
fadeInAnimation.duration = 1.0f;
fadeInAnimation.removedOnCompletion = NO;
fadeInAnimation.fillMode = kCAFillModeForwards;
fadeInAnimation.toValue = [NSNumber numberWithFloat:1.0];
[dataSourceLinePlot addAnimation:fadeInAnimation forKey:@"animateOpacity"];
// Add some initial data
NSMutableArray *contentArray = [NSMutableArray arrayWithCapacity:100];
NSUInteger i;
for ( i = 0; i < 60; i++ ) {
id x = [NSNumber numberWithFloat:1+i*0.05];
id y = [NSNumber numberWithFloat:1.2*rand()/(float)RAND_MAX + 1.2];
[contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x, @"x", y, @"y", nil]];
}
self.dataForPlot = contentArray;
#ifdef PERFORMANCE_TEST
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(changePlotRange) userInfo:nil repeats:YES];
#endif
}
-(void)changePlotRange
{
// Setup plot space
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0) length:CPDecimalFromFloat(3.0 + 2.0*rand()/RAND_MAX)];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0) length:CPDecimalFromFloat(3.0 + 2.0*rand()/RAND_MAX)];
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot {
return [dataForPlot count];
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSNumber *num = [[dataForPlot objectAtIndex:index] valueForKey:(fieldEnum == CPScatterPlotFieldX ? @"x" : @"y")];
// Green plot gets shifted above the blue
if ([(NSString *)plot.identifier isEqualToString:@"Green Plot"])
{
if ( fieldEnum == CPScatterPlotFieldY )
num = [NSNumber numberWithDouble:[num doubleValue] + 1.0];
}
return num;
}
@end
| 08iteng-ipad | examples/CPTestApp-iPhone/Classes/CPTestAppScatterPlotController.m | Objective-C | bsd | 6,940 |
//
// CPTestAppScatterPlotController.h
// CPTestApp-iPhone
//
// Created by Brad Larson on 5/11/2009.
//
#import <UIKit/UIKit.h>
#import "CorePlot-CocoaTouch.h"
@interface CPTestAppScatterPlotController : UIViewController <CPPlotDataSource>
{
CPXYGraph *graph;
NSMutableArray *dataForPlot;
}
@property(readwrite, retain, nonatomic) NSMutableArray *dataForPlot;
@end
| 08iteng-ipad | examples/CPTestApp-iPhone/Classes/CPTestAppScatterPlotController.h | Objective-C | bsd | 377 |
//
// CPTestAppBarChartController.m
// CPTestApp-iPhone
//
#import "CPTestAppBarChartController.h"
@implementation CPTestAppBarChartController
@synthesize timer;
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
return YES;
}
#pragma mark -
#pragma mark Initialization and teardown
-(void)viewDidAppear:(BOOL)animated
{
[self timerFired];
#ifdef MEMORY_TEST
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self
selector:@selector(timerFired) userInfo:nil repeats:YES];
#endif
}
-(void)timerFired
{
#ifdef MEMORY_TEST
static NSUInteger counter = 0;
NSLog(@"\n----------------------------\ntimerFired: %lu", counter++);
#endif
[barChart release];
// Create barChart from theme
barChart = [[CPXYGraph alloc] initWithFrame:CGRectZero];
CPTheme *theme = [CPTheme themeNamed:kCPDarkGradientTheme];
[barChart applyTheme:theme];
CPGraphHostingView *hostingView = (CPGraphHostingView *)self.view;
hostingView.hostedGraph = barChart;
// Border
barChart.plotAreaFrame.borderLineStyle = nil;
barChart.plotAreaFrame.cornerRadius = 0.0f;
// Paddings
barChart.paddingLeft = 0.0f;
barChart.paddingRight = 0.0f;
barChart.paddingTop = 0.0f;
barChart.paddingBottom = 0.0f;
barChart.plotAreaFrame.paddingLeft = 70.0;
barChart.plotAreaFrame.paddingTop = 20.0;
barChart.plotAreaFrame.paddingRight = 20.0;
barChart.plotAreaFrame.paddingBottom = 80.0;
// Graph title
barChart.title = @"Graph Title";
CPMutableTextStyle *textStyle = [CPTextStyle textStyle];
textStyle.color = [CPColor grayColor];
textStyle.fontSize = 16.0f;
barChart.titleTextStyle = textStyle;
barChart.titleDisplacement = CGPointMake(0.0f, -20.0f);
barChart.titlePlotAreaFrameAnchor = CPRectAnchorTop;
// Add plot space for horizontal bar charts
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)barChart.defaultPlotSpace;
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0f) length:CPDecimalFromFloat(300.0f)];
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0f) length:CPDecimalFromFloat(16.0f)];
CPXYAxisSet *axisSet = (CPXYAxisSet *)barChart.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.axisLineStyle = nil;
x.majorTickLineStyle = nil;
x.minorTickLineStyle = nil;
x.majorIntervalLength = CPDecimalFromString(@"5");
x.orthogonalCoordinateDecimal = CPDecimalFromString(@"0");
x.title = @"X Axis";
x.titleLocation = CPDecimalFromFloat(7.5f);
x.titleOffset = 55.0f;
// Define some custom labels for the data elements
x.labelRotation = M_PI/4;
x.labelingPolicy = CPAxisLabelingPolicyNone;
NSArray *customTickLocations = [NSArray arrayWithObjects:[NSDecimalNumber numberWithInt:1], [NSDecimalNumber numberWithInt:5], [NSDecimalNumber numberWithInt:10], [NSDecimalNumber numberWithInt:15], nil];
NSArray *xAxisLabels = [NSArray arrayWithObjects:@"Label A", @"Label B", @"Label C", @"Label D", @"Label E", nil];
NSUInteger labelLocation = 0;
NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:[xAxisLabels count]];
for (NSNumber *tickLocation in customTickLocations) {
CPAxisLabel *newLabel = [[CPAxisLabel alloc] initWithText: [xAxisLabels objectAtIndex:labelLocation++] textStyle:x.labelTextStyle];
newLabel.tickLocation = [tickLocation decimalValue];
newLabel.offset = x.labelOffset + x.majorTickLength;
newLabel.rotation = M_PI/4;
[customLabels addObject:newLabel];
[newLabel release];
}
x.axisLabels = [NSSet setWithArray:customLabels];
CPXYAxis *y = axisSet.yAxis;
y.axisLineStyle = nil;
y.majorTickLineStyle = nil;
y.minorTickLineStyle = nil;
y.majorIntervalLength = CPDecimalFromString(@"50");
y.orthogonalCoordinateDecimal = CPDecimalFromString(@"0");
y.title = @"Y Axis";
y.titleOffset = 45.0f;
y.titleLocation = CPDecimalFromFloat(150.0f);
// First bar plot
CPBarPlot *barPlot = [CPBarPlot tubularBarPlotWithColor:[CPColor darkGrayColor] horizontalBars:NO];
barPlot.baseValue = CPDecimalFromString(@"0");
barPlot.dataSource = self;
barPlot.barOffset = CPDecimalFromFloat(-0.25f);
barPlot.identifier = @"Bar Plot 1";
[barChart addPlot:barPlot toPlotSpace:plotSpace];
// Second bar plot
barPlot = [CPBarPlot tubularBarPlotWithColor:[CPColor blueColor] horizontalBars:NO];
barPlot.dataSource = self;
barPlot.baseValue = CPDecimalFromString(@"0");
barPlot.barOffset = CPDecimalFromFloat(0.25f);
barPlot.barCornerRadius = 2.0f;
barPlot.identifier = @"Bar Plot 2";
[barChart addPlot:barPlot toPlotSpace:plotSpace];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot {
return 16;
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSDecimalNumber *num = nil;
if ( [plot isKindOfClass:[CPBarPlot class]] ) {
switch ( fieldEnum ) {
case CPBarPlotFieldBarLocation:
num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:index];
break;
case CPBarPlotFieldBarTip:
num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:(index+1)*(index+1)];
if ( [plot.identifier isEqual:@"Bar Plot 2"] )
num = [num decimalNumberBySubtracting:[NSDecimalNumber decimalNumberWithString:@"10"]];
break;
}
}
return num;
}
-(CPFill *) barFillForBarPlot:(CPBarPlot *)barPlot recordIndex:(NSNumber *)index;
{
return nil;
}
@end
| 08iteng-ipad | examples/CPTestApp-iPhone/Classes/CPTestAppBarChartController.m | Objective-C | bsd | 5,765 |
#import "Controller.h"
#import <CorePlot/CorePlot.h>
@implementation Controller
-(void)dealloc
{
[plotData release];
[graph release];
[super dealloc];
}
-(void)awakeFromNib
{
[super awakeFromNib];
// If you make sure your dates are calculated at noon, you shouldn't have to
// worry about daylight savings. If you use midnight, you will have to adjust
// for daylight savings time.
NSDate *refDate = [NSDate dateWithNaturalLanguageString:@"00:00 Oct 29, 2009"];
NSTimeInterval oneDay = 24 * 60 * 60;
// Create graph from theme
graph = [(CPXYGraph *)[CPXYGraph alloc] initWithFrame:CGRectZero];
CPTheme *theme = [CPTheme themeNamed:kCPDarkGradientTheme];
[graph applyTheme:theme];
hostView.hostedLayer = graph;
// Setup scatter plot space
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
NSTimeInterval xLow = 0.0f;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(xLow) length:CPDecimalFromFloat(oneDay*3.0f)];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(1.0) length:CPDecimalFromFloat(3.0)];
// Axes
CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.majorIntervalLength = CPDecimalFromFloat(oneDay);
x.orthogonalCoordinateDecimal = CPDecimalFromString(@"2");
x.minorTicksPerInterval = 3;
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateStyle = kCFDateFormatterShortStyle;
CPTimeFormatter *myDateFormatter = [[[CPTimeFormatter alloc] initWithDateFormatter:dateFormatter] autorelease];
myDateFormatter.referenceDate = refDate;
x.labelFormatter = myDateFormatter;
NSDateFormatter *timeFormatter = [[[NSDateFormatter alloc] init] autorelease];
timeFormatter.timeStyle = kCFDateFormatterShortStyle;
CPTimeFormatter *myTimeFormatter = [[[CPTimeFormatter alloc] initWithDateFormatter:timeFormatter] autorelease];
myTimeFormatter.referenceDate = refDate;
x.minorTickLabelFormatter = myTimeFormatter;
// x.minorTickLabelRotation = M_PI/2;
CPXYAxis *y = axisSet.yAxis;
y.majorIntervalLength = CPDecimalFromString(@"0.5");
y.minorTicksPerInterval = 5;
y.orthogonalCoordinateDecimal = CPDecimalFromFloat(0.5*oneDay);
// Create a plot that uses the data source method
CPScatterPlot *dataSourceLinePlot = [[[CPScatterPlot alloc] init] autorelease];
dataSourceLinePlot.identifier = @"Date Plot";
CPMutableLineStyle *lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.lineWidth = 3.f;
lineStyle.lineColor = [CPColor greenColor];
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.dataSource = self;
[graph addPlot:dataSourceLinePlot];
// Add some data
NSMutableArray *newData = [NSMutableArray array];
NSUInteger i;
for ( i = 0; i < 7; i++ ) {
NSTimeInterval x = oneDay*i*0.5f;
id y = [NSDecimalNumber numberWithFloat:1.2*rand()/(float)RAND_MAX + 1.2];
[newData addObject:
[NSDictionary dictionaryWithObjectsAndKeys:
[NSDecimalNumber numberWithFloat:x], [NSNumber numberWithInt:CPScatterPlotFieldX],
y, [NSNumber numberWithInt:CPScatterPlotFieldY],
nil]];
}
plotData = newData;
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
return plotData.count;
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSDecimalNumber *num = [[plotData objectAtIndex:index] objectForKey:[NSNumber numberWithInt:fieldEnum]];
return num;
}
@end
| 08iteng-ipad | examples/MinorTickLabels/Controller.m | Objective-C | bsd | 3,732 |
//
// main.m
// CPTestApp
//
// Created by Dirkjan Krijnders on 2/2/09.
// Copyright __MyCompanyName__ 2009. All rights reserved.
//
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **) argv);
}
| 08iteng-ipad | examples/MinorTickLabels/Source/main.m | Objective-C | bsd | 259 |
#import <Cocoa/Cocoa.h>
#import <CorePlot/CorePlot.h>
@interface Controller : NSObject <CPPlotDataSource> {
IBOutlet CPLayerHostingView *hostView;
CPXYGraph *graph;
NSArray *plotData;
}
@end
| 08iteng-ipad | examples/MinorTickLabels/Controller.h | Objective-C | bsd | 208 |
//
// PlotView.m
// CorePlotGallery
//
// Created by Jeff Buck on 9/6/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "PlotView.h"
@implementation PlotView
@synthesize delegate;
- (id)initWithFrame:(NSRect)frame
{
if ((self = [super initWithFrame:frame])) {
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect
{
}
- (void)setFrameSize:(NSSize)newSize
{
[super setFrameSize:newSize];
if (delegate && [delegate respondsToSelector:@selector(setFrameSize:)])
[delegate setFrameSize:newSize];
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/mac/PlotView.m | Objective-C | bsd | 555 |
//
// Plot_Gallery_MacAppDelegate.m
// CorePlotGallery
//
// Created by Jeff Buck on 9/5/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "Plot_Gallery_MacAppDelegate.h"
@implementation Plot_Gallery_MacAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
}
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
{
return YES;
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/mac/Plot_Gallery_MacAppDelegate.m | Objective-C | bsd | 439 |
//
// PlotGalleryController.m
// CorePlotGallery
//
// Created by Jeff Buck on 9/5/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "PlotGalleryController.h"
#import "dlfcn.h"
//#define EMBED_NU 1
const float CP_SPLIT_VIEW_MIN_LHS_WIDTH = 150.0f;
#define kThemeTableViewControllerNoTheme @"None"
#define kThemeTableViewControllerDefaultTheme @"Default"
@implementation PlotGalleryController
@dynamic plotItem;
@synthesize currentThemeName;
- (void)setupThemes
{
[themePopUpButton addItemWithTitle:kThemeTableViewControllerDefaultTheme];
[themePopUpButton addItemWithTitle:kThemeTableViewControllerNoTheme];
for (Class c in [CPTheme themeClasses]) {
[themePopUpButton addItemWithTitle:[c defaultName]];
}
self.currentThemeName = kThemeTableViewControllerDefaultTheme;
[themePopUpButton selectItemWithTitle:kThemeTableViewControllerDefaultTheme];
}
- (void)awakeFromNib
{
[[PlotGallery sharedPlotGallery] sortByTitle];
[splitView setDelegate:self];
[imageBrowser setDelegate:self];
[imageBrowser setDataSource:self];
[imageBrowser setCellsStyleMask:IKCellsStyleShadowed | IKCellsStyleTitled ]; //| IKCellsStyleSubtitled];
[imageBrowser reloadData];
[hostingView setDelegate:self];
[self setupThemes];
#ifdef EMBED_NU
// Setup a Nu console without the help of the Nu include files or
// an explicit link of the Nu framework, which may not be installed
nuHandle = dlopen("/Library/Frameworks/Nu.framework/Nu", RTLD_LAZY);
if (nuHandle)
{
NSString *consoleStartup =
@"(progn \
(load \"console\") \
(set $console ((NuConsoleWindowController alloc) init)))";
Class nuClass = NSClassFromString(@"Nu");
id parser = [nuClass performSelector:@selector(parser)];
id code = [parser performSelector:@selector(parse:) withObject:consoleStartup];
[parser performSelector:@selector(eval:) withObject:code];
}
#endif
}
- (void)dealloc
{
[self setPlotItem:nil];
[splitView setDelegate:nil];
[imageBrowser setDataSource:nil];
[imageBrowser setDelegate:nil];
[hostingView setDelegate:nil];
#ifdef EMBED_NU
if (nuHandle) dlclose(nuHandle);
#endif
[super dealloc];
}
- (void)setFrameSize:(NSSize)newSize
{
if ([plotItem respondsToSelector:@selector(setFrameSize:)]) {
[plotItem setFrameSize:newSize];
}
}
#pragma mark -
#pragma mark Theme Selection
- (CPTheme *)currentTheme
{
CPTheme *theme;
if (currentThemeName == kThemeTableViewControllerNoTheme) {
theme = (id)[NSNull null];
}
else if (currentThemeName == kThemeTableViewControllerDefaultTheme) {
theme = nil;
}
else {
theme = [CPTheme themeNamed:currentThemeName];
}
return theme;
}
- (IBAction)themeSelectionDidChange:(id)sender
{
self.currentThemeName = [sender titleOfSelectedItem];
[plotItem renderInView:hostingView withTheme:[self currentTheme]];
}
#pragma mark -
#pragma mark PlotItem Property
- (PlotItem *)plotItem
{
return plotItem;
}
- (void)setPlotItem:(PlotItem *)item
{
if (plotItem != item) {
[plotItem killGraph];
[plotItem release];
plotItem = [item retain];
[plotItem renderInView:hostingView withTheme:[self currentTheme]];
}
}
#pragma mark IKImageBrowserViewDataSource methods
- (NSUInteger)numberOfItemsInImageBrowser:(IKImageBrowserView *)browser
{
return [[PlotGallery sharedPlotGallery] count];
}
- (id)imageBrowser:(IKImageBrowserView *)browser itemAtIndex:(NSUInteger)index
{
return [[PlotGallery sharedPlotGallery] objectAtIndex:index];
}
#pragma mark IKImageBrowserViewDelegate methods
- (void)imageBrowserSelectionDidChange:(IKImageBrowserView *)browser
{
int index = [[browser selectionIndexes] firstIndex];
if (index >= 0) {
PlotItem *item = [[PlotGallery sharedPlotGallery] objectAtIndex:index];
self.plotItem = item;
}
}
#pragma mark NSSplitViewDelegate methods
- (CGFloat)splitView:(NSSplitView *)sv constrainMinCoordinate:(CGFloat)coord ofSubviewAt:(NSInteger)index
{
return coord + CP_SPLIT_VIEW_MIN_LHS_WIDTH;
}
- (CGFloat)splitView:(NSSplitView *)sv constrainMaxCoordinate:(CGFloat)coord ofSubviewAt:(NSInteger)index
{
return coord - CP_SPLIT_VIEW_MIN_LHS_WIDTH;
}
- (void)splitView:(NSSplitView*)sender resizeSubviewsWithOldSize:(NSSize)oldSize
{
// Lock the LHS width
NSRect frame = [sender frame];
NSView *lhs = [[sender subviews] objectAtIndex:0];
NSRect lhsRect = [lhs frame];
NSView *rhs = [[sender subviews] objectAtIndex:1];
NSRect rhsRect = [rhs frame];
CGFloat dividerThickness = [sender dividerThickness];
lhsRect.size.height = frame.size.height;
rhsRect.size.width = frame.size.width - lhsRect.size.width - dividerThickness;
rhsRect.size.height = frame.size.height;
rhsRect.origin.x = lhsRect.size.width + dividerThickness;
[lhs setFrame:lhsRect];
[rhs setFrame:rhsRect];
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/mac/PlotGalleryController.m | Objective-C | bsd | 5,046 |
//
// PlotView.h
// CorePlotGallery
//
// Created by Jeff Buck on 9/6/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@protocol PlotViewDelegate <NSObject>
- (void)setFrameSize:(NSSize)newSize;
@end
@interface PlotView : NSView
{
id<PlotViewDelegate> delegate;
}
@property (nonatomic, retain) id<PlotViewDelegate> delegate;
@end
| 08iteng-ipad | examples/CorePlotGallery/src/mac/PlotView.h | Objective-C | bsd | 378 |
//
// main.m
// CorePlotGallery
//
// Created by Jeff Buck on 9/5/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **)argv);
}
| 08iteng-ipad | examples/CorePlotGallery/src/mac/main.m | Objective-C | bsd | 247 |
//
// Plot_Gallery_MacAppDelegate.h
// CorePlotGallery
//
// Created by Jeff Buck on 9/5/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface Plot_Gallery_MacAppDelegate : NSObject <NSApplicationDelegate>
{
NSWindow *window;
}
@property (assign) IBOutlet NSWindow *window;
@end
| 08iteng-ipad | examples/CorePlotGallery/src/mac/Plot_Gallery_MacAppDelegate.h | Objective-C | bsd | 329 |
//
// PlotGalleryController.h
// CorePlotGallery
//
// Created by Jeff Buck on 9/5/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import <Cocoa/Cocoa.h>
#import <Quartz/Quartz.h>
#import <CorePlot/CorePlot.h>
#import "PlotGallery.h"
#import "PlotView.h"
@interface PlotGalleryController : NSObject <NSSplitViewDelegate,
PlotViewDelegate>
{
IBOutlet NSSplitView *splitView;
IBOutlet NSScrollView *scrollView;
IBOutlet IKImageBrowserView *imageBrowser;
IBOutlet NSPopUpButton *themePopUpButton;
IBOutlet PlotView *hostingView;
CPLayerHostingView *defaultLayerHostingView;
PlotItem *plotItem;
NSString *currentThemeName;
void *nuHandle;
}
@property (nonatomic, retain) PlotItem *plotItem;
@property (nonatomic, copy) NSString *currentThemeName;
- (IBAction)themeSelectionDidChange:(id)sender;
@end
| 08iteng-ipad | examples/CorePlotGallery/src/mac/PlotGalleryController.h | Objective-C | bsd | 999 |
//
// CompositePlot.h
// CorePlotGallery
//
// Created by Jeff Buck on 9/4/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
#import "CorePlot-CocoaTouch.h"
#else
#import <CorePlot/CorePlot.h>
#endif
#import "PlotItem.h"
#import "PlotGallery.h"
@interface CompositePlot : PlotItem <CPPlotSpaceDelegate,
CPPlotDataSource,
CPScatterPlotDelegate,
CPBarPlotDelegate>
{
CPGraphHostingView *scatterPlotView;
CPGraphHostingView *barChartView;
CPGraphHostingView *pieChartView;
CPXYGraph *scatterPlot;
CPXYGraph *barChart;
CPXYGraph *pieChart;
NSMutableArray *dataForChart;
NSMutableArray *dataForPlot;
}
@property(readwrite, retain, nonatomic) NSMutableArray *dataForChart;
@property(readwrite, retain, nonatomic) NSMutableArray *dataForPlot;
- (void)renderScatterPlotInLayer:(CPGraphHostingView *)layerHostingView withTheme:(CPTheme *)theme;
- (void)renderBarPlotInLayer:(CPGraphHostingView *)layerHostingView withTheme:(CPTheme *)theme;
- (void)renderPieChartInLayer:(CPGraphHostingView *)layerHostingView withTheme:(CPTheme *)theme;
@end
| 08iteng-ipad | examples/CorePlotGallery/src/plots/CompositePlot.h | Objective-C | bsd | 1,209 |
//
// GradientScatterPlot.h
// CorePlotGallery
//
// Created by Jeff Buck on 8/2/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "PlotItem.h"
#import "PlotGallery.h"
@interface GradientScatterPlot : PlotItem < CPPlotSpaceDelegate,
CPPlotDataSource,
CPScatterPlotDelegate>
{
CPLayerAnnotation *symbolTextAnnotation;
CGFloat xShift;
CGFloat yShift;
CGFloat labelRotation;
NSArray* plotData;
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/plots/GradientScatterPlot.h | Objective-C | bsd | 580 |
#import "DonutChart.h"
NSString * const innerChartName = @"Inner";
NSString * const outerChartName = @"Outer";
@implementation DonutChart
+ (void)load
{
[super registerPlotItem:self];
}
- (id)init
{
if ((self = [super init])) {
title = @"Donut Chart";
}
return self;
}
- (void)killGraph
{
[super killGraph];
}
- (void)dealloc
{
[plotData release];
[super dealloc];
}
- (void)generateData
{
if (plotData == nil) {
plotData = [[NSMutableArray alloc] initWithObjects:
[NSNumber numberWithDouble:20.0],
[NSNumber numberWithDouble:30.0],
[NSNumber numberWithDouble:60.0],
nil];
}
}
- (void)renderInLayer:(CPGraphHostingView *)layerHostingView withTheme:(CPTheme *)theme
{
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
CGRect bounds = layerHostingView.bounds;
#else
CGRect bounds = NSRectToCGRect(layerHostingView.bounds);
#endif
CPGraph *graph = [[[CPXYGraph alloc] initWithFrame:[layerHostingView bounds]] autorelease];
[self addGraph:graph toHostingView:layerHostingView];
[self applyTheme:theme toGraph:graph withDefault:[CPTheme themeNamed:kCPDarkGradientTheme]];
graph.title = title;
CPMutableTextStyle *textStyle = [CPMutableTextStyle textStyle];
textStyle.color = [CPColor grayColor];
textStyle.fontName = @"Helvetica-Bold";
textStyle.fontSize = bounds.size.height / 20.0f;
graph.titleTextStyle = textStyle;
graph.titleDisplacement = CGPointMake(0.0f, bounds.size.height / 18.0f);
graph.titlePlotAreaFrameAnchor = CPRectAnchorTop;
graph.plotAreaFrame.masksToBorder = NO;
// Graph padding
float boundsPadding = bounds.size.width / 20.0f;
graph.paddingLeft = boundsPadding;
graph.paddingTop = graph.titleDisplacement.y * 2;
graph.paddingRight = boundsPadding;
graph.paddingBottom = boundsPadding;
graph.axisSet = nil;
CPMutableLineStyle *whiteLineStyle = [CPMutableLineStyle lineStyle];
whiteLineStyle.lineColor = [CPColor whiteColor];
// Add pie chart
CPPieChart *piePlot = [[CPPieChart alloc] init];
piePlot.dataSource = self;
piePlot.pieRadius = MIN(0.7 * (layerHostingView.frame.size.height - 2 * graph.paddingLeft) / 2.0,
0.7 * (layerHostingView.frame.size.width - 2 * graph.paddingTop) / 2.0);
CGFloat innerRadius = piePlot.pieRadius / 2.0;
piePlot.pieInnerRadius = innerRadius + 5.0;
piePlot.identifier = outerChartName;
piePlot.borderLineStyle = whiteLineStyle;
piePlot.startAngle = M_PI_4;
piePlot.sliceDirection = CPPieDirectionCounterClockwise;
piePlot.delegate = self;
[graph addPlot:piePlot];
[piePlot release];
// Add another pie chart
piePlot = [[CPPieChart alloc] init];
piePlot.dataSource = self;
piePlot.pieRadius = innerRadius - 5.0;
piePlot.identifier = innerChartName;
piePlot.borderLineStyle = whiteLineStyle;
piePlot.startAngle = M_PI_4;
piePlot.sliceDirection = CPPieDirectionClockwise;
piePlot.delegate = self;
[graph addPlot:piePlot];
[piePlot release];
[self generateData];
}
-(void)pieChart:(CPPieChart *)plot sliceWasSelectedAtRecordIndex:(NSUInteger)index
{
NSLog(@"%@ slice was selected at index %lu. Value = %@", plot.identifier, index, [plotData objectAtIndex:index]);
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
return [plotData count];
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSNumber *num;
if (fieldEnum == CPPieChartFieldSliceWidth) {
num = [plotData objectAtIndex:index];
}
else {
return [NSNumber numberWithInt:index];
}
return num;
}
-(CPLayer *)dataLabelForPlot:(CPPlot *)plot recordIndex:(NSUInteger)index
{
static CPMutableTextStyle *whiteText = nil;
CPTextLayer *newLayer = nil;
if ( [(NSString *)plot.identifier isEqualToString:outerChartName] ) {
if ( !whiteText ) {
whiteText = [[CPMutableTextStyle alloc] init];
whiteText.color = [CPColor whiteColor];
}
newLayer = [[[CPTextLayer alloc] initWithText:[NSString stringWithFormat:@"%3.0f", [[plotData objectAtIndex:index] floatValue]] style:whiteText] autorelease];
}
return newLayer;
}
-(CGFloat)radialOffsetForPieChart:(CPPieChart *)pieChart recordIndex:(NSUInteger)index
{
CGFloat result = 0.0;
if ( [(NSString *)pieChart.identifier isEqualToString:outerChartName] ) {
result = ( index == 0 ? 15.0 : 0.0 );
}
return result;
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/plots/DonutChart.m | Objective-C | bsd | 4,609 |
//
// SimpleScatterPlot.m
// CorePlotGallery
//
// Created by Jeff Buck on 7/31/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "SimpleScatterPlot.h"
@implementation SimpleScatterPlot
+ (void)load
{
[super registerPlotItem:self];
}
- (id)init
{
if ((self = [super init])) {
title = @"Simple Scatter Plot";
}
return self;
}
- (void)killGraph
{
if ([graphs count]) {
CPGraph *graph = [graphs objectAtIndex:0];
if (symbolTextAnnotation) {
[graph.plotAreaFrame.plotArea removeAnnotation:symbolTextAnnotation];
[symbolTextAnnotation release];
symbolTextAnnotation = nil;
}
}
[super killGraph];
}
- (void)generateData
{
if (plotData == nil) {
NSMutableArray *contentArray = [NSMutableArray array];
for (NSUInteger i = 0; i < 10; i++) {
id x = [NSDecimalNumber numberWithDouble:1.0 + i * 0.05];
id y = [NSDecimalNumber numberWithDouble:1.2 * rand()/(double)RAND_MAX + 0.5];
[contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x, @"x", y, @"y", nil]];
}
plotData = [contentArray retain];
}
}
- (void)renderInLayer:(CPGraphHostingView *)layerHostingView withTheme:(CPTheme *)theme
{
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
CGRect bounds = layerHostingView.bounds;
#else
CGRect bounds = NSRectToCGRect(layerHostingView.bounds);
#endif
CPGraph *graph = [[[CPXYGraph alloc] initWithFrame:[layerHostingView bounds]] autorelease];
[self addGraph:graph toHostingView:layerHostingView];
[self applyTheme:theme toGraph:graph withDefault:[CPTheme themeNamed:kCPDarkGradientTheme]];
[self setTitleDefaultsForGraph:graph withBounds:bounds];
[self setPaddingDefaultsForGraph:graph withBounds:bounds];
// Setup scatter plot space
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
plotSpace.delegate = self;
// Grid line styles
CPMutableLineStyle *majorGridLineStyle = [CPMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [[CPColor colorWithGenericGray:0.2] colorWithAlphaComponent:0.75];
CPMutableLineStyle *minorGridLineStyle = [CPMutableLineStyle lineStyle];
minorGridLineStyle.lineWidth = 0.25;
minorGridLineStyle.lineColor = [[CPColor whiteColor] colorWithAlphaComponent:0.1];
CPMutableLineStyle *redLineStyle = [CPMutableLineStyle lineStyle];
redLineStyle.lineWidth = 10.0;
redLineStyle.lineColor = [[CPColor redColor] colorWithAlphaComponent:0.5];
// Axes
// Label x axis with a fixed interval policy
CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.majorIntervalLength = CPDecimalFromString(@"0.5");
x.orthogonalCoordinateDecimal = CPDecimalFromString(@"1.0");
x.minorTicksPerInterval = 2;
x.majorGridLineStyle = majorGridLineStyle;
x.minorGridLineStyle = minorGridLineStyle;
x.title = @"X Axis";
x.titleOffset = 30.0;
x.titleLocation = CPDecimalFromString(@"1.25");
// Label y with an automatic label policy.
CPXYAxis *y = axisSet.yAxis;
y.labelingPolicy = CPAxisLabelingPolicyAutomatic;
y.orthogonalCoordinateDecimal = CPDecimalFromString(@"1.0");
y.minorTicksPerInterval = 2;
y.preferredNumberOfMajorTicks = 8;
y.majorGridLineStyle = majorGridLineStyle;
y.minorGridLineStyle = minorGridLineStyle;
y.labelOffset = 10.0;
y.title = @"Y Axis";
y.titleOffset = 30.0;
y.titleLocation = CPDecimalFromString(@"1.0");
// Rotate the labels by 45 degrees, just to show it can be done.
labelRotation = M_PI * 0.25;
// Set axes
//graph.axisSet.axes = [NSArray arrayWithObjects:x, y, y2, nil];
graph.axisSet.axes = [NSArray arrayWithObjects:x, y, nil];
// Create a plot that uses the data source method
CPScatterPlot *dataSourceLinePlot = [[[CPScatterPlot alloc] init] autorelease];
dataSourceLinePlot.identifier = @"Data Source Plot";
CPMutableLineStyle *lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.lineWidth = 3.0;
lineStyle.lineColor = [CPColor greenColor];
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.dataSource = self;
[graph addPlot:dataSourceLinePlot];
[self generateData];
// Auto scale the plot space to fit the plot data
// Extend the y range by 10% for neatness
[plotSpace scaleToFitPlots:[NSArray arrayWithObjects:dataSourceLinePlot, nil]];
CPPlotRange *xRange = plotSpace.xRange;
CPPlotRange *yRange = plotSpace.yRange;
[xRange expandRangeByFactor:CPDecimalFromDouble(1.3)];
[yRange expandRangeByFactor:CPDecimalFromDouble(1.3)];
plotSpace.yRange = yRange;
// Restrict y range to a global range
CPPlotRange *globalYRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0f)
length:CPDecimalFromFloat(2.0f)];
plotSpace.globalYRange = globalYRange;
// set the x and y shift to match the new ranges
CGFloat length = xRange.lengthDouble;
xShift = length - 3.0;
length = yRange.lengthDouble;
yShift = length - 2.0;
// Add plot symbols
CPMutableLineStyle *symbolLineStyle = [CPMutableLineStyle lineStyle];
symbolLineStyle.lineColor = [CPColor blackColor];
CPPlotSymbol *plotSymbol = [CPPlotSymbol ellipsePlotSymbol];
plotSymbol.fill = [CPFill fillWithColor:[CPColor blueColor]];
plotSymbol.lineStyle = symbolLineStyle;
plotSymbol.size = CGSizeMake(10.0, 10.0);
dataSourceLinePlot.plotSymbol = plotSymbol;
// Set plot delegate, to know when symbols have been touched
// We will display an annotation when a symbol is touched
dataSourceLinePlot.delegate = self;
dataSourceLinePlot.plotSymbolMarginForHitDetection = 5.0f;
}
- (void)dealloc
{
[symbolTextAnnotation release];
[plotData release];
[super dealloc];
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
return [plotData count];
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSNumber *num = [[plotData objectAtIndex:index] valueForKey:(fieldEnum == CPScatterPlotFieldX ? @"x" : @"y")];
if (fieldEnum == CPScatterPlotFieldY) {
num = [NSNumber numberWithDouble:[num doubleValue]];
}
return num;
}
#pragma mark -
#pragma mark Plot Space Delegate Methods
-(CPPlotRange *)plotSpace:(CPPlotSpace *)space willChangePlotRangeTo:(CPPlotRange *)newRange forCoordinate:(CPCoordinate)coordinate
{
// Impose a limit on how far user can scroll in x
if (coordinate == CPCoordinateX) {
CPPlotRange *maxRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-1.0f) length:CPDecimalFromFloat(6.0f)];
CPPlotRange *changedRange = [[newRange copy] autorelease];
[changedRange shiftEndToFitInRange:maxRange];
[changedRange shiftLocationToFitInRange:maxRange];
newRange = changedRange;
}
return newRange;
}
#pragma mark -
#pragma mark CPScatterPlot delegate method
-(void)scatterPlot:(CPScatterPlot *)plot plotSymbolWasSelectedAtRecordIndex:(NSUInteger)index
{
CPXYGraph *graph = [graphs objectAtIndex:0];
if (symbolTextAnnotation) {
[graph.plotAreaFrame.plotArea removeAnnotation:symbolTextAnnotation];
[symbolTextAnnotation release];
symbolTextAnnotation = nil;
}
// Setup a style for the annotation
CPMutableTextStyle *hitAnnotationTextStyle = [CPMutableTextStyle textStyle];
hitAnnotationTextStyle.color = [CPColor whiteColor];
hitAnnotationTextStyle.fontSize = 16.0f;
hitAnnotationTextStyle.fontName = @"Helvetica-Bold";
// Determine point of symbol in plot coordinates
NSNumber *x = [[plotData objectAtIndex:index] valueForKey:@"x"];
NSNumber *y = [[plotData objectAtIndex:index] valueForKey:@"y"];
NSArray *anchorPoint = [NSArray arrayWithObjects:x, y, nil];
// Add annotation
// First make a string for the y value
NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setMaximumFractionDigits:2];
NSString *yString = [formatter stringFromNumber:y];
// Now add the annotation to the plot area
CPTextLayer *textLayer = [[[CPTextLayer alloc] initWithText:yString style:hitAnnotationTextStyle] autorelease];
symbolTextAnnotation = [[CPPlotSpaceAnnotation alloc] initWithPlotSpace:graph.defaultPlotSpace anchorPlotPoint:anchorPoint];
symbolTextAnnotation.contentLayer = textLayer;
symbolTextAnnotation.displacement = CGPointMake(0.0f, 20.0f);
[graph.plotAreaFrame.plotArea addAnnotation:symbolTextAnnotation];
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/plots/SimpleScatterPlot.m | Objective-C | bsd | 8,917 |
//
// SimpleBarGraph.h
// CorePlotGallery
//
// Created by Jeff Buck on 7/31/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "PlotItem.h"
#import "PlotGallery.h"
@interface VerticalBarChart : PlotItem <CPPlotSpaceDelegate,
CPPlotDataSource,
CPBarPlotDelegate>
{
CPLayerAnnotation *symbolTextAnnotation;
CGFloat xShift;
CGFloat yShift;
CGFloat labelRotation;
NSArray *plotData;
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/plots/VerticalBarChart.h | Objective-C | bsd | 561 |
//
// SimplePieChart.m
// CorePlotGallery
//
// Created by Jeff Buck on 8/2/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "SimplePieChart.h"
@implementation SimplePieChart
+ (void)load
{
[super registerPlotItem:self];
}
- (id)init
{
if ((self = [super init])) {
title = @"Simple Pie Chart";
}
return self;
}
- (void)killGraph
{
[super killGraph];
}
- (void)dealloc
{
[plotData release];
[super dealloc];
}
- (void)generateData
{
if (plotData == nil) {
plotData = [[NSMutableArray alloc] initWithObjects:
[NSNumber numberWithDouble:20.0],
[NSNumber numberWithDouble:30.0],
[NSNumber numberWithDouble:60.0],
nil];
}
}
- (void)renderInLayer:(CPGraphHostingView *)layerHostingView withTheme:(CPTheme *)theme
{
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
CGRect bounds = layerHostingView.bounds;
#else
CGRect bounds = NSRectToCGRect(layerHostingView.bounds);
#endif
CPGraph *graph = [[[CPXYGraph alloc] initWithFrame:[layerHostingView bounds]] autorelease];
[self addGraph:graph toHostingView:layerHostingView];
[self applyTheme:theme toGraph:graph withDefault:[CPTheme themeNamed:kCPDarkGradientTheme]];
graph.title = title;
CPMutableTextStyle *textStyle = [CPMutableTextStyle textStyle];
textStyle.color = [CPColor grayColor];
textStyle.fontName = @"Helvetica-Bold";
textStyle.fontSize = bounds.size.height / 20.0f;
graph.titleTextStyle = textStyle;
graph.titleDisplacement = CGPointMake(0.0f, bounds.size.height / 18.0f);
graph.titlePlotAreaFrameAnchor = CPRectAnchorTop;
graph.plotAreaFrame.masksToBorder = NO;
// Graph padding
float boundsPadding = bounds.size.width / 20.0f;
graph.paddingLeft = boundsPadding;
graph.paddingTop = graph.titleDisplacement.y * 2;
graph.paddingRight = boundsPadding;
graph.paddingBottom = boundsPadding;
graph.axisSet = nil;
// Add pie chart
CPPieChart *piePlot = [[CPPieChart alloc] init];
piePlot.dataSource = self;
piePlot.pieRadius = MIN(0.7 * (layerHostingView.frame.size.height - 2 * graph.paddingLeft) / 2.0,
0.7 * (layerHostingView.frame.size.width - 2 * graph.paddingTop) / 2.0);
piePlot.identifier = title;
piePlot.startAngle = M_PI_4;
piePlot.sliceDirection = CPPieDirectionCounterClockwise;
piePlot.delegate = self;
[graph addPlot:piePlot];
[piePlot release];
[self generateData];
}
-(CPLayer *)dataLabelForPlot:(CPPlot *)plot recordIndex:(NSUInteger)index
{
static CPMutableTextStyle *whiteText = nil;
if (!whiteText) {
whiteText = [[CPMutableTextStyle alloc] init];
whiteText.color = [CPColor whiteColor];
}
CPTextLayer *newLayer = [[[CPTextLayer alloc] initWithText:[NSString stringWithFormat:@"%3.0f", [[plotData objectAtIndex:index] floatValue]]
style:whiteText] autorelease];
return newLayer;
}
-(void)pieChart:(CPPieChart *)plot sliceWasSelectedAtRecordIndex:(NSUInteger)index
{
NSLog(@"Slice was selected at index %d. Value = %f", (int)index, [[plotData objectAtIndex:index] floatValue]);
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
return [plotData count];
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSNumber *num;
if (fieldEnum == CPPieChartFieldSliceWidth) {
num = [plotData objectAtIndex:index];
}
else {
return [NSNumber numberWithInt:index];
}
return num;
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/plots/SimplePieChart.m | Objective-C | bsd | 3,726 |
#import "PlotItem.h"
#import "PlotGallery.h"
@interface DonutChart : PlotItem <CPPlotSpaceDelegate, CPPlotDataSource>
{
NSArray *plotData;
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/plots/DonutChart.h | Objective-C | bsd | 152 |
//
// DatePlot.h
// Plot Gallery-Mac
//
// Created by Jeff Buck on 11/14/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "PlotItem.h"
#import "PlotGallery.h"
@interface DatePlot : PlotItem < CPPlotSpaceDelegate,
CPPlotDataSource,
CPScatterPlotDelegate>
{
CGFloat labelRotation;
NSArray *plotData;
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/plots/DatePlot.h | Objective-C | bsd | 414 |
//
// AxisDemo.m
// Plot Gallery-Mac
//
// Created by Jeff Buck on 11/14/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "AxisDemo.h"
@implementation AxisDemo
+ (void)load
{
// Not working yet...
//[super registerPlotItem:self];
}
- (id)init
{
if ((self = [super init])) {
title = @"Axis Demo";
}
return self;
}
- (void)generateData
{
if (plotData == nil) {
NSMutableArray *contentArray = [NSMutableArray array];
for (NSUInteger i = 0; i < 10; i++) {
id x = [NSDecimalNumber numberWithDouble:1.0 + i * 0.05];
id y = [NSDecimalNumber numberWithDouble:1.2 * rand()/(double)RAND_MAX + 0.5];
[contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x, @"x", y, @"y", nil]];
}
plotData = [contentArray retain];
}
}
- (void)renderInLayer:(CPGraphHostingView *)layerHostingView withTheme:(CPTheme *)theme
{
#if TARGET_OS_IPHONE
CGRect bounds = layerHostingView.bounds;
#else
CGRect bounds = NSRectToCGRect(layerHostingView.bounds);
#endif
// Create graph
CPGraph* graph = [[[CPXYGraph alloc] initWithFrame:[layerHostingView bounds]] autorelease];
[self addGraph:graph toHostingView:layerHostingView];
[self applyTheme:theme toGraph:graph withDefault:[CPTheme themeNamed:kCPSlateTheme]];
[self setTitleDefaultsForGraph:graph withBounds:bounds];
[self setPaddingDefaultsForGraph:graph withBounds:bounds];
graph.fill = [CPFill fillWithColor:[CPColor darkGrayColor]];
graph.cornerRadius = 20.0;
// Plot area
graph.plotAreaFrame.fill = [CPFill fillWithColor:[CPColor lightGrayColor]];
graph.plotAreaFrame.paddingTop = 20.0;
graph.plotAreaFrame.paddingBottom = 50.0;
graph.plotAreaFrame.paddingLeft = 50.0;
graph.plotAreaFrame.paddingRight = 20.0;
graph.plotAreaFrame.cornerRadius = 10.0;
graph.plotAreaFrame.axisSet.borderLineStyle = [CPLineStyle lineStyle];
graph.plotAreaFrame.plotArea.fill = [CPFill fillWithColor:[CPColor whiteColor]];
// Setup plot space
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(-10.0)];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.5) length:CPDecimalFromDouble(10.0)];
// Line styles
CPMutableLineStyle *axisLineStyle = [CPMutableLineStyle lineStyle];
axisLineStyle.lineWidth = 3.0;
axisLineStyle.lineCap = kCGLineCapRound;
CPMutableLineStyle *majorGridLineStyle = [CPMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [CPColor redColor];
CPMutableLineStyle *minorGridLineStyle = [CPMutableLineStyle lineStyle];
minorGridLineStyle.lineWidth = 0.25;
minorGridLineStyle.lineColor = [CPColor blueColor];
// Text styles
CPMutableTextStyle *axisTitleTextStyle = [CPMutableTextStyle textStyle];
axisTitleTextStyle.fontName = @"Helvetica Bold";
axisTitleTextStyle.fontSize = 14.0;
// Axes
// Label x axis with a fixed interval policy
CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.separateLayers = NO;
x.orthogonalCoordinateDecimal = CPDecimalFromDouble(0.5);
x.majorIntervalLength = CPDecimalFromString(@"0.5");
x.minorTicksPerInterval = 4;
x.tickDirection = CPSignNone;
x.axisLineStyle = axisLineStyle;
x.majorTickLength = 12.0;
x.majorTickLineStyle = axisLineStyle;
x.majorGridLineStyle = majorGridLineStyle;
x.minorTickLength = 8.0;
x.minorGridLineStyle = minorGridLineStyle;
x.title = @"X Axis";
x.titleTextStyle = axisTitleTextStyle;
x.titleOffset = 25.0;
x.alternatingBandFills = [NSArray arrayWithObjects:[[CPColor redColor] colorWithAlphaComponent:0.1], [[CPColor greenColor] colorWithAlphaComponent:0.1], nil];
// Label y with an automatic label policy.
axisLineStyle.lineColor = [CPColor greenColor];
CPXYAxis *y = axisSet.yAxis;
y.separateLayers = YES;
y.minorTicksPerInterval = 9;
y.tickDirection = CPSignNone;
y.axisLineStyle = axisLineStyle;
y.majorTickLength = 12.0;
y.majorTickLineStyle = axisLineStyle;
y.majorGridLineStyle = majorGridLineStyle;
y.minorTickLength = 8.0;
y.minorGridLineStyle = minorGridLineStyle;
y.title = @"Y Axis";
y.titleTextStyle = axisTitleTextStyle;
y.titleOffset = 30.0;
y.alternatingBandFills = [NSArray arrayWithObjects:[[CPColor blueColor] colorWithAlphaComponent:0.1], [NSNull null], nil];
CPFill *bandFill = [CPFill fillWithColor:[[CPColor darkGrayColor] colorWithAlphaComponent:0.5]];
[y addBackgroundLimitBand:[CPLimitBand limitBandWithRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(7.0) length:CPDecimalFromDouble(1.5)] fill:bandFill]];
[y addBackgroundLimitBand:[CPLimitBand limitBandWithRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(1.5) length:CPDecimalFromDouble(3.0)] fill:bandFill]];
}
- (void)dealloc
{
[plotData release];
[super dealloc];
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
return [plotData count];
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSNumber* num = [[plotData objectAtIndex:index] valueForKey:(fieldEnum == CPScatterPlotFieldX ? @"x" : @"y")];
if (fieldEnum == CPScatterPlotFieldY) {
num = [NSNumber numberWithDouble:[num doubleValue]];
}
return num;
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/plots/AxisDemo.m | Objective-C | bsd | 5,553 |
//
// GradientScatterPlot.m
// CorePlotGallery
//
// Created by Jeff Buck on 8/2/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "GradientScatterPlot.h"
@implementation GradientScatterPlot
+ (void)load
{
[super registerPlotItem:self];
}
- (id)init
{
if ((self = [super init])) {
title = @"Gradient Scatter Plot";
}
return self;
}
- (void)killGraph
{
if ([graphs count]) {
CPGraph *graph = [graphs objectAtIndex:0];
if (symbolTextAnnotation) {
[graph.plotAreaFrame.plotArea removeAnnotation:symbolTextAnnotation];
[symbolTextAnnotation release];
symbolTextAnnotation = nil;
}
}
[super killGraph];
}
- (void)generateData
{
if (plotData == nil) {
NSMutableArray *contentArray = [NSMutableArray arrayWithCapacity:100];
for (NSUInteger i = 0; i < 10; i++) {
id x = [NSDecimalNumber numberWithDouble:1.0 + i * 0.05];
id y = [NSDecimalNumber numberWithDouble:1.2 * rand()/(double)RAND_MAX + 0.5];
[contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x, @"x", y, @"y", nil]];
}
plotData = [contentArray retain];
}
}
- (void)renderInLayer:(CPGraphHostingView *)layerHostingView withTheme:(CPTheme *)theme
{
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
CGRect bounds = layerHostingView.bounds;
#else
CGRect bounds = NSRectToCGRect(layerHostingView.bounds);
#endif
CPGraph* graph = [[[CPXYGraph alloc] initWithFrame:[layerHostingView bounds]] autorelease];
[self addGraph:graph toHostingView:layerHostingView];
[self applyTheme:theme toGraph:graph withDefault:[CPTheme themeNamed:kCPSlateTheme]];
[self setTitleDefaultsForGraph:graph withBounds:bounds];
[self setPaddingDefaultsForGraph:graph withBounds:bounds];
// Setup scatter plot space
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
plotSpace.delegate = self;
// Grid line styles
CPMutableLineStyle *majorGridLineStyle = [CPMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [[CPColor colorWithGenericGray:0.2] colorWithAlphaComponent:0.75];
CPMutableLineStyle *minorGridLineStyle = [CPMutableLineStyle lineStyle];
minorGridLineStyle.lineWidth = 0.25;
minorGridLineStyle.lineColor = [[CPColor whiteColor] colorWithAlphaComponent:0.1];
CPMutableLineStyle *redLineStyle = [CPMutableLineStyle lineStyle];
redLineStyle.lineWidth = 10.0;
redLineStyle.lineColor = [[CPColor redColor] colorWithAlphaComponent:0.5];
// Axes
// Label x axis with a fixed interval policy
CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.majorIntervalLength = CPDecimalFromString(@"0.5");
x.orthogonalCoordinateDecimal = CPDecimalFromString(@"1.0");
x.minorTicksPerInterval = 2;
x.majorGridLineStyle = majorGridLineStyle;
x.minorGridLineStyle = minorGridLineStyle;
x.title = @"X Axis";
x.titleOffset = 30.0;
x.titleLocation = CPDecimalFromString(@"1.25");
// Label y with an automatic label policy.
CPXYAxis *y = axisSet.yAxis;
y.labelingPolicy = CPAxisLabelingPolicyAutomatic;
y.orthogonalCoordinateDecimal = CPDecimalFromString(@"1.0");
y.minorTicksPerInterval = 2;
y.preferredNumberOfMajorTicks = 8;
y.majorGridLineStyle = majorGridLineStyle;
y.minorGridLineStyle = minorGridLineStyle;
y.labelOffset = 10.0;
y.title = @"Y Axis";
y.titleOffset = 30.0;
y.titleLocation = CPDecimalFromString(@"1.0");
// Rotate the labels by 45 degrees, just to show it can be done.
labelRotation = M_PI * 0.25;
// Add an extra y axis (red)
// We add constraints to this axis below
CPXYAxis *y2 = [[(CPXYAxis *)[CPXYAxis alloc] initWithFrame:CGRectZero] autorelease];
y2.labelingPolicy = CPAxisLabelingPolicyAutomatic;
y2.orthogonalCoordinateDecimal = CPDecimalFromString(@"3");
y2.minorTicksPerInterval = 0;
y2.preferredNumberOfMajorTicks = 4;
y2.majorGridLineStyle = majorGridLineStyle;
y2.minorGridLineStyle = minorGridLineStyle;
y2.labelOffset = 10.0;
y2.coordinate = CPCoordinateY;
y2.plotSpace = graph.defaultPlotSpace;
y2.axisLineStyle = redLineStyle;
y2.majorTickLineStyle = redLineStyle;
y2.minorTickLineStyle = nil;
y2.labelTextStyle = nil;
y2.visibleRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromInteger(2) length:CPDecimalFromInteger(3)];
// Set axes
//graph.axisSet.axes = [NSArray arrayWithObjects:x, y, y2, nil];
graph.axisSet.axes = [NSArray arrayWithObjects:x, y, y2, nil];
// Put an area gradient under the plot above
//NSString *pathToFillImage = [[NSBundle mainBundle] pathForResource:@"BlueTexture" ofType:@"png"];
//CPImage *fillImage = [CPImage imageForPNGFile:pathToFillImage];
//fillImage.tiled = YES;
//CPFill *areaGradientFill = [CPFill fillWithImage:fillImage];
// Create a plot that uses the data source method
CPScatterPlot *dataSourceLinePlot = [[[CPScatterPlot alloc] init] autorelease];
dataSourceLinePlot.identifier = @"Data Source Plot";
CPMutableLineStyle *lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.lineWidth = 3.0;
lineStyle.lineColor = [CPColor greenColor];
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.dataSource = self;
[graph addPlot:dataSourceLinePlot];
// Put an area gradient under the plot above
CPColor *areaColor = [CPColor colorWithComponentRed:0.3 green:1.0 blue:0.3 alpha:0.8];
CPGradient *areaGradient = [CPGradient gradientWithBeginningColor:areaColor endingColor:[CPColor clearColor]];
areaGradient.angle = -90.0;
CPFill* areaGradientFill = [CPFill fillWithGradient:areaGradient];
dataSourceLinePlot.areaFill = areaGradientFill;
dataSourceLinePlot.areaBaseValue = CPDecimalFromString(@"0.0");
[self generateData];
// Auto scale the plot space to fit the plot data
// Extend the y range by 10% for neatness
[plotSpace scaleToFitPlots:[NSArray arrayWithObjects:dataSourceLinePlot, nil]];
CPPlotRange *xRange = plotSpace.xRange;
CPPlotRange *yRange = plotSpace.yRange;
[xRange expandRangeByFactor:CPDecimalFromDouble(1.3)];
[yRange expandRangeByFactor:CPDecimalFromDouble(1.3)];
plotSpace.yRange = yRange;
// Restrict y range to a global range
CPPlotRange *globalYRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0f)
length:CPDecimalFromFloat(2.0f)];
plotSpace.globalYRange = globalYRange;
// set the x and y shift to match the new ranges
CGFloat length = xRange.lengthDouble;
xShift = length - 3.0;
length = yRange.lengthDouble;
yShift = length - 2.0;
// Position y2 axis relative to the plot area, ie, not moving when dragging
CPConstraints y2Constraints = {CPConstraintNone, CPConstraintFixed};
y2.isFloatingAxis = YES;
y2.constraints = y2Constraints;
// Add plot symbols
CPMutableLineStyle *symbolLineStyle = [CPMutableLineStyle lineStyle];
symbolLineStyle.lineColor = [CPColor blackColor];
CPPlotSymbol *plotSymbol = [CPPlotSymbol ellipsePlotSymbol];
plotSymbol.fill = [CPFill fillWithColor:[CPColor blueColor]];
plotSymbol.lineStyle = symbolLineStyle;
plotSymbol.size = CGSizeMake(10.0, 10.0);
dataSourceLinePlot.plotSymbol = plotSymbol;
// Set plot delegate, to know when symbols have been touched
// We will display an annotation when a symbol is touched
dataSourceLinePlot.delegate = self;
dataSourceLinePlot.plotSymbolMarginForHitDetection = 5.0f;
}
- (void)dealloc
{
[plotData release];
[super dealloc];
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
return [plotData count];
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSNumber* num = [[plotData objectAtIndex:index] valueForKey:(fieldEnum == CPScatterPlotFieldX ? @"x" : @"y")];
if (fieldEnum == CPScatterPlotFieldY) {
num = [NSNumber numberWithDouble:[num doubleValue]];
}
return num;
}
#pragma mark -
#pragma mark Plot Space Delegate Methods
-(CPPlotRange *)plotSpace:(CPPlotSpace *)space willChangePlotRangeTo:(CPPlotRange *)newRange forCoordinate:(CPCoordinate)coordinate
{
// Impose a limit on how far user can scroll in x
if ( coordinate == CPCoordinateX ) {
CPPlotRange *maxRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-1.0f) length:CPDecimalFromFloat(6.0f)];
CPPlotRange *changedRange = [[newRange copy] autorelease];
[changedRange shiftEndToFitInRange:maxRange];
[changedRange shiftLocationToFitInRange:maxRange];
newRange = changedRange;
}
return newRange;
}
#pragma mark -
#pragma mark CPScatterPlot delegate method
-(void)scatterPlot:(CPScatterPlot *)plot plotSymbolWasSelectedAtRecordIndex:(NSUInteger)index
{
CPGraph* graph = [graphs objectAtIndex:0];
if ( symbolTextAnnotation ) {
[graph.plotAreaFrame.plotArea removeAnnotation:symbolTextAnnotation];
symbolTextAnnotation = nil;
}
// Setup a style for the annotation
CPMutableTextStyle *hitAnnotationTextStyle = [CPMutableTextStyle textStyle];
hitAnnotationTextStyle.color = [CPColor whiteColor];
hitAnnotationTextStyle.fontSize = 16.0f;
hitAnnotationTextStyle.fontName = @"Helvetica-Bold";
// Determine point of symbol in plot coordinates
NSNumber *x = [[plotData objectAtIndex:index] valueForKey:@"x"];
NSNumber *y = [[plotData objectAtIndex:index] valueForKey:@"y"];
NSArray *anchorPoint = [NSArray arrayWithObjects:x, y, nil];
// Add annotation
// First make a string for the y value
NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setMaximumFractionDigits:2];
NSString *yString = [formatter stringFromNumber:y];
// Now add the annotation to the plot area
CPTextLayer *textLayer = [[[CPTextLayer alloc] initWithText:yString style:hitAnnotationTextStyle] autorelease];
symbolTextAnnotation = [[CPPlotSpaceAnnotation alloc] initWithPlotSpace:graph.defaultPlotSpace anchorPlotPoint:anchorPoint];
symbolTextAnnotation.contentLayer = textLayer;
symbolTextAnnotation.displacement = CGPointMake(0.0f, 20.0f);
[graph.plotAreaFrame.plotArea addAnnotation:symbolTextAnnotation];
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/plots/GradientScatterPlot.m | Objective-C | bsd | 10,705 |
//
// DatePlot.m
// Plot Gallery-Mac
//
// Created by Jeff Buck on 11/14/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "DatePlot.h"
@implementation DatePlot
+ (void)load
{
[super registerPlotItem:self];
}
- (id)init
{
if ((self = [super init])) {
title = @"Date Plot";
}
return self;
}
- (void)generateData
{
NSTimeInterval oneDay = 24 * 60 * 60;
// Add some data
NSMutableArray *newData = [NSMutableArray array];
NSUInteger i;
for ( i = 0; i < 5; i++ ) {
NSTimeInterval x = oneDay*i;
id y = [NSDecimalNumber numberWithFloat:1.2*rand()/(float)RAND_MAX + 1.2];
[newData addObject:
[NSDictionary dictionaryWithObjectsAndKeys:
[NSDecimalNumber numberWithFloat:x], [NSNumber numberWithInt:CPScatterPlotFieldX],
y, [NSNumber numberWithInt:CPScatterPlotFieldY],
nil]];
}
plotData = [newData retain];
}
- (void)renderInLayer:(CPGraphHostingView *)layerHostingView withTheme:(CPTheme *)theme
{
// If you make sure your dates are calculated at noon, you shouldn't have to
// worry about daylight savings. If you use midnight, you will have to adjust
// for daylight savings time.
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setMonth:10];
[dateComponents setDay:29];
[dateComponents setYear:2009];
[dateComponents setHour:12];
[dateComponents setMinute:0];
[dateComponents setSecond:0];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *refDate = [gregorian dateFromComponents:dateComponents];
[dateComponents release];
[gregorian release];
NSTimeInterval oneDay = 24 * 60 * 60;
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
CGRect bounds = layerHostingView.bounds;
#else
CGRect bounds = NSRectToCGRect(layerHostingView.bounds);
#endif
CPGraph *graph = [[[CPXYGraph alloc] initWithFrame:[layerHostingView bounds]] autorelease];
[self addGraph:graph toHostingView:layerHostingView];
[self applyTheme:theme toGraph:graph withDefault:[CPTheme themeNamed:kCPDarkGradientTheme]];
[self setTitleDefaultsForGraph:graph withBounds:bounds];
[self setPaddingDefaultsForGraph:graph withBounds:bounds];
// Setup scatter plot space
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
NSTimeInterval xLow = 0.0f;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(xLow) length:CPDecimalFromFloat(oneDay*5.0f)];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(1.0) length:CPDecimalFromFloat(3.0)];
// Axes
CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.majorIntervalLength = CPDecimalFromFloat(oneDay);
x.orthogonalCoordinateDecimal = CPDecimalFromString(@"2");
x.minorTicksPerInterval = 0;
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateStyle = kCFDateFormatterShortStyle;
CPTimeFormatter *timeFormatter = [[[CPTimeFormatter alloc] initWithDateFormatter:dateFormatter] autorelease];
timeFormatter.referenceDate = refDate;
x.labelFormatter = timeFormatter;
x.labelRotation = M_PI/4;
CPXYAxis *y = axisSet.yAxis;
y.majorIntervalLength = CPDecimalFromString(@"0.5");
y.minorTicksPerInterval = 5;
y.orthogonalCoordinateDecimal = CPDecimalFromFloat(oneDay);
[self generateData];
// Create a plot that uses the data source method
CPScatterPlot *dataSourceLinePlot = [[[CPScatterPlot alloc] init] autorelease];
dataSourceLinePlot.identifier = @"Date Plot";
CPMutableLineStyle *lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.lineWidth = 3.f;
lineStyle.lineColor = [CPColor greenColor];
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.dataSource = self;
[graph addPlot:dataSourceLinePlot];
}
- (void)dealloc
{
[plotData release];
[super dealloc];
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
return [plotData count];
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSDecimalNumber *num = [[plotData objectAtIndex:index] objectForKey:[NSNumber numberWithInt:fieldEnum]];
return num;
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/plots/DatePlot.m | Objective-C | bsd | 4,442 |
//
// SimpleScatterPlot.h
// CorePlotGallery
//
// Created by Jeff Buck on 7/31/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "PlotItem.h"
#import "PlotGallery.h"
@interface SimpleScatterPlot : PlotItem < CPPlotSpaceDelegate,
CPPlotDataSource,
CPScatterPlotDelegate>
{
CPLayerAnnotation *symbolTextAnnotation;
CGFloat xShift;
CGFloat yShift;
CGFloat labelRotation;
NSArray* plotData;
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/plots/SimpleScatterPlot.h | Objective-C | bsd | 573 |
//
// SteppedScatterPlot.h
// Plot Gallery-Mac
//
// Created by Jeff Buck on 11/14/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "PlotItem.h"
#import "PlotGallery.h"
@interface SteppedScatterPlot : PlotItem <CPPlotSpaceDelegate,
CPPlotDataSource,
CPScatterPlotDelegate>
{
CGFloat xShift;
CGFloat yShift;
CGFloat labelRotation;
NSArray *plotData;
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/plots/SteppedScatterPlot.h | Objective-C | bsd | 505 |
//
// AxisDemo.h
// Plot Gallery-Mac
//
// Created by Jeff Buck on 11/14/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "PlotItem.h"
#import "PlotGallery.h"
@interface AxisDemo : PlotItem <CPPlotSpaceDelegate,
CPPlotDataSource>
{
NSMutableArray *plotData;
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/plots/AxisDemo.h | Objective-C | bsd | 324 |
//
// SimplePieChart.h
// CorePlotGallery
//
// Created by Jeff Buck on 8/2/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "PlotItem.h"
#import "PlotGallery.h"
@interface SimplePieChart : PlotItem <CPPlotSpaceDelegate,
CPPlotDataSource>
{
NSArray *plotData;
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/plots/SimplePieChart.h | Objective-C | bsd | 305 |
//
// SimpleBarGraph.m
// CorePlotGallery
//
// Created by Jeff Buck on 7/31/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "VerticalBarChart.h"
@implementation VerticalBarChart
+ (void)load
{
[super registerPlotItem:self];
}
- (id)init
{
if ((self = [super init])) {
title = @"Vertical Bar Chart";
}
return self;
}
- (void)killGraph
{
if ([graphs count]) {
CPGraph *graph = [graphs objectAtIndex:0];
if (symbolTextAnnotation) {
[graph.plotAreaFrame.plotArea removeAnnotation:symbolTextAnnotation];
[symbolTextAnnotation release];
symbolTextAnnotation = nil;
}
}
[super killGraph];
}
- (void)generateData
{
}
#define HORIZONTAL 0
- (void)renderInLayer:(CPGraphHostingView *)layerHostingView withTheme:(CPTheme *)theme
{
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
CGRect bounds = layerHostingView.bounds;
#else
CGRect bounds = NSRectToCGRect(layerHostingView.bounds);
#endif
CPGraph *graph = [[CPXYGraph alloc] initWithFrame:bounds];
[self addGraph:graph toHostingView:layerHostingView];
[self applyTheme:theme toGraph:graph withDefault:[CPTheme themeNamed:kCPDarkGradientTheme]];
[self setTitleDefaultsForGraph:graph withBounds:bounds];
[self setPaddingDefaultsForGraph:graph withBounds:bounds];
// Add plot space for bar charts
CPXYPlotSpace *barPlotSpace = [[[CPXYPlotSpace alloc] init] autorelease];
#if HORIZONTAL
barPlotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-10.0f) length:CPDecimalFromFloat(120.0f)];
barPlotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-1.0f) length:CPDecimalFromFloat(11.0f)];
#else
barPlotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-1.0f) length:CPDecimalFromFloat(11.0f)];
barPlotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-10.0f) length:CPDecimalFromFloat(120.0f)];
#endif
[graph addPlotSpace:barPlotSpace];
// Create grid line styles
CPMutableLineStyle *majorGridLineStyle = [CPMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 1.0f;
majorGridLineStyle.lineColor = [[CPColor whiteColor] colorWithAlphaComponent:0.75];
CPMutableLineStyle *minorGridLineStyle = [CPMutableLineStyle lineStyle];
minorGridLineStyle.lineWidth = 1.0f;
minorGridLineStyle.lineColor = [[CPColor whiteColor] colorWithAlphaComponent:0.25];
// Create axes
CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet;
CPXYAxis *x = axisSet.xAxis;
{
#if HORIZONTAL
x.majorIntervalLength = CPDecimalFromInteger(10);
x.minorTicksPerInterval = 9;
#else
x.majorIntervalLength = CPDecimalFromInteger(1);
x.minorTicksPerInterval = 0;
#endif
x.orthogonalCoordinateDecimal = CPDecimalFromInteger(0);
x.majorGridLineStyle = majorGridLineStyle;
x.minorGridLineStyle = minorGridLineStyle;
x.axisLineStyle = nil;
x.majorTickLineStyle = nil;
x.minorTickLineStyle = nil;
x.labelOffset = 10.0;
#if HORIZONTAL
x.visibleRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0f) length:CPDecimalFromFloat(100.0f)];
x.gridLinesRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-0.5f) length:CPDecimalFromFloat(10.0f)];
#else
x.visibleRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-0.5f) length:CPDecimalFromFloat(10.0f)];
x.gridLinesRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0f) length:CPDecimalFromFloat(100.0f)];
#endif
x.title = @"X Axis";
x.titleOffset = 30.0f;
#if HORIZONTAL
x.titleLocation = CPDecimalFromInteger(55);
#else
x.titleLocation = CPDecimalFromInteger(5);
#endif
x.plotSpace = barPlotSpace;
}
CPXYAxis *y = axisSet.yAxis;
{
#if HORIZONTAL
y.majorIntervalLength = CPDecimalFromInteger(1);
y.minorTicksPerInterval = 0;
#else
y.majorIntervalLength = CPDecimalFromInteger(10);
y.minorTicksPerInterval = 9;
#endif
y.orthogonalCoordinateDecimal = CPDecimalFromInteger(0);
y.preferredNumberOfMajorTicks = 8;
y.majorGridLineStyle = majorGridLineStyle;
y.minorGridLineStyle = minorGridLineStyle;
y.axisLineStyle = nil;
y.majorTickLineStyle = nil;
y.minorTickLineStyle = nil;
y.labelOffset = 10.0;
y.labelRotation = M_PI/2;
#if HORIZONTAL
y.visibleRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-0.5f) length:CPDecimalFromFloat(10.0f)];
y.gridLinesRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0f) length:CPDecimalFromFloat(100.0f)];
#else
y.visibleRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0f) length:CPDecimalFromFloat(100.0f)];
y.gridLinesRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-0.5f) length:CPDecimalFromFloat(10.0f)];
#endif
y.title = @"Y Axis";
y.titleOffset = 30.0f;
#if HORIZONTAL
y.titleLocation = CPDecimalFromInteger(5);
#else
y.titleLocation = CPDecimalFromInteger(55);
#endif
y.plotSpace = barPlotSpace;
}
// Set axes
graph.axisSet.axes = [NSArray arrayWithObjects:x, y, nil];
// Create a bar line style
CPMutableLineStyle *barLineStyle = [[[CPMutableLineStyle alloc] init] autorelease];
barLineStyle.lineWidth = 1.0;
barLineStyle.lineColor = [CPColor whiteColor];
// Create first bar plot
CPBarPlot *barPlot = [[[CPBarPlot alloc] init] autorelease];
barPlot.lineStyle = barLineStyle;
barPlot.fill = [CPFill fillWithColor:[CPColor colorWithComponentRed:1.0f green:0.0f blue:0.5f alpha:0.5f]];
barPlot.barBasesVary = YES;
barPlot.barWidth = CPDecimalFromFloat(0.5f); // bar is 50% of the available space
barPlot.barCornerRadius = 10.0f;
#if HORIZONTAL
barPlot.barsAreHorizontal = YES;
#else
barPlot.barsAreHorizontal = NO;
#endif
CPMutableTextStyle *whiteTextStyle = [CPMutableTextStyle textStyle];
whiteTextStyle.color = [CPColor whiteColor];
barPlot.barLabelTextStyle = whiteTextStyle;
barPlot.delegate = self;
barPlot.dataSource = self;
barPlot.identifier = @"Bar Plot 1";
[graph addPlot:barPlot toPlotSpace:barPlotSpace];
// Create second bar plot
CPBarPlot *barPlot2 = [CPBarPlot tubularBarPlotWithColor:[CPColor blueColor] horizontalBars:NO];
barPlot2.lineStyle = barLineStyle;
barPlot2.fill = [CPFill fillWithColor:[CPColor colorWithComponentRed:0.0f green:1.0f blue:0.5f alpha:0.5f]];
barPlot2.barBasesVary = YES;
barPlot2.barWidth = CPDecimalFromFloat(1.0f); // bar is full (100%) width
// barPlot2.barOffset = -0.125f; // shifted left by 12.5%
barPlot2.barCornerRadius = 2.0f;
#if HORIZONTAL
barPlot2.barsAreHorizontal = YES;
#else
barPlot2.barsAreHorizontal = NO;
#endif
barPlot2.delegate = self;
barPlot2.dataSource = self;
barPlot2.identifier = @"Bar Plot 2";
[graph addPlot:barPlot2 toPlotSpace:barPlotSpace];
}
- (void)dealloc
{
[plotData release];
[super dealloc];
}
-(CPFill *)barFillForBarPlot:(CPBarPlot *)barPlot recordIndex:(NSUInteger)index
{
return nil;
}
-(CPLayer *)dataLabelForPlot:(CPPlot *)plot recordIndex:(NSUInteger)index
{
return nil;
}
#pragma mark -
#pragma mark CPBarPlot delegate method
-(void)barPlot:(CPBarPlot *)plot barWasSelectedAtRecordIndex:(NSUInteger)index
{
NSNumber *value = [self numberForPlot:plot field:CPBarPlotFieldBarTip recordIndex:index];
NSLog(@"bar was selected at index %d. Value = %f", (int)index, [value floatValue]);
CPGraph *graph = [graphs objectAtIndex:0];
if ( symbolTextAnnotation ) {
[graph.plotAreaFrame.plotArea removeAnnotation:symbolTextAnnotation];
symbolTextAnnotation = nil;
}
// Setup a style for the annotation
CPMutableTextStyle *hitAnnotationTextStyle = [CPMutableTextStyle textStyle];
hitAnnotationTextStyle.color = [CPColor orangeColor];
hitAnnotationTextStyle.fontSize = 16.0f;
hitAnnotationTextStyle.fontName = @"Helvetica-Bold";
// Determine point of symbol in plot coordinates
NSNumber *x = [NSNumber numberWithInt:index];
NSNumber *y = [NSNumber numberWithInt:2]; //[self numberForPlot:plot field:0 recordIndex:index];
#if HORIZONTAL
NSArray *anchorPoint = [NSArray arrayWithObjects:y, x, nil];
#else
NSArray *anchorPoint = [NSArray arrayWithObjects:x, y, nil];
#endif
// Add annotation
// First make a string for the y value
NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setMaximumFractionDigits:2];
NSString *yString = [formatter stringFromNumber:value];
// Now add the annotation to the plot area
CPTextLayer *textLayer = [[[CPTextLayer alloc] initWithText:yString style:hitAnnotationTextStyle] autorelease];
symbolTextAnnotation = [[CPPlotSpaceAnnotation alloc] initWithPlotSpace:plot.plotSpace anchorPlotPoint:anchorPoint];
symbolTextAnnotation.contentLayer = textLayer;
symbolTextAnnotation.displacement = CGPointMake(0.0f, 0.0f);
[graph.plotAreaFrame.plotArea addAnnotation:symbolTextAnnotation];
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
return 10;
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSNumber *num = nil;
if (fieldEnum == CPBarPlotFieldBarLocation) {
// location
if ([plot.identifier isEqual:@"Bar Plot 2"]) {
num = [NSDecimalNumber numberWithInt:index];
}
else {
num = [NSDecimalNumber numberWithInt:index];
}
}
else if (fieldEnum == CPBarPlotFieldBarTip) {
// length
if ([plot.identifier isEqual:@"Bar Plot 2"]) {
num = [NSDecimalNumber numberWithInt:index];
}
else {
num = [NSDecimalNumber numberWithInt:(index+1)*(index+1)];
}
}
else {
// base
if ([plot.identifier isEqual:@"Bar Plot 2"]) {
num = [NSDecimalNumber numberWithInt:0];
}
else {
num = [NSDecimalNumber numberWithInt:index];
}
}
NSLog(@"identifier = %@, field = %ld, index = %ld -> %@", plot.identifier, fieldEnum, index, num);
return num;
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/plots/VerticalBarChart.m | Objective-C | bsd | 9,995 |
//
// CompositePlot.m
// CorePlotGallery
//
// Created by Jeff Buck on 9/4/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
#import "CorePlot-CocoaTouch.h"
#else
#import <CorePlot/CorePlot.h>
#endif
#import "CompositePlot.h"
@implementation CompositePlot
@synthesize dataForChart;
@synthesize dataForPlot;
+ (void)load
{
[super registerPlotItem:self];
}
- (id)init
{
if ( (self = [super init]) ) {
title = @"Composite Plot";
}
return self;
}
#pragma mark -
#pragma mark Plot construction methods
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
#else
- (void)setFrameSize:(NSSize)newSize
{
scatterPlotView.frame = NSMakeRect(0.0f,
0.0f,
newSize.width,
newSize.height * 0.5f);
barChartView.frame = NSMakeRect(0.0f,
newSize.height * 0.5f,
newSize.width * 0.5f,
newSize.height * 0.5f);
pieChartView.frame = NSMakeRect(newSize.width * 0.5f,
newSize.height * 0.5f,
newSize.width * 0.5f,
newSize.height * 0.5f);
[scatterPlotView needsDisplay];
[barChartView needsDisplay];
[pieChartView needsDisplay];
}
#endif
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
- (void)renderInView:(UIView *)hostingView withTheme:(CPTheme *)theme
#else
- (void)renderInView:(NSView *)hostingView withTheme:(CPTheme *)theme
#endif
{
[self killGraph];
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
CGRect viewRect = [hostingView bounds];
scatterPlotView = [[CPGraphHostingView alloc] initWithFrame:CGRectMake(0.0f,
0.0f,
viewRect.size.width,
viewRect.size.height * 0.5f)];
barChartView = [[CPGraphHostingView alloc] initWithFrame:CGRectMake(0.0f,
viewRect.size.height * 0.5f,
viewRect.size.width * 0.5f,
viewRect.size.height * 0.5f)];
pieChartView = [[CPGraphHostingView alloc] initWithFrame:CGRectMake(viewRect.size.width * 0.5f,
viewRect.size.height * 0.5f,
viewRect.size.width * 0.5f,
viewRect.size.height * 0.5f)];
#else
NSRect viewRect = [hostingView bounds];
scatterPlotView = [[CPGraphHostingView alloc] initWithFrame:NSMakeRect(0.0f,
0.0f,
viewRect.size.width,
viewRect.size.height * 0.5f)];
barChartView = [[CPGraphHostingView alloc] initWithFrame:NSMakeRect(0.0f,
viewRect.size.height * 0.5f,
viewRect.size.width * 0.5f,
viewRect.size.height * 0.5f)];
pieChartView = [[CPGraphHostingView alloc] initWithFrame:NSMakeRect(viewRect.size.width * 0.5f,
viewRect.size.height * 0.5f,
viewRect.size.width * 0.5f,
viewRect.size.height * 0.5f)];
[scatterPlotView setAutoresizesSubviews:YES];
[scatterPlotView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[barChartView setAutoresizesSubviews:YES];
[barChartView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[pieChartView setAutoresizesSubviews:YES];
[pieChartView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
#endif
[hostingView addSubview:scatterPlotView];
[hostingView addSubview:barChartView];
[hostingView addSubview:pieChartView];
[self renderScatterPlotInLayer:scatterPlotView withTheme:theme];
[self renderBarPlotInLayer:barChartView withTheme:theme];
[self renderPieChartInLayer:pieChartView withTheme:theme];
}
- (void)killGraph
{
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
scatterPlotView.hostedGraph = nil;
barChartView.hostedGraph = nil;
pieChartView.hostedGraph = nil;
#else
scatterPlotView.hostedLayer = nil;
barChartView.hostedLayer = nil;
pieChartView.hostedLayer = nil;
#endif
[scatterPlotView removeFromSuperview];
[barChartView removeFromSuperview];
[pieChartView removeFromSuperview];
[scatterPlotView release];
[barChartView release];
[pieChartView release];
scatterPlotView = nil;
barChartView = nil;
pieChartView = nil;
[super killGraph];
}
- (void)renderScatterPlotInLayer:(CPGraphHostingView *)layerHostingView withTheme:(CPTheme *)theme
{
// Create graph from theme
scatterPlot = [[CPXYGraph alloc] initWithFrame:[scatterPlotView bounds]];
[self addGraph:scatterPlot toHostingView:layerHostingView];
[self applyTheme:theme toGraph:scatterPlot withDefault:[CPTheme themeNamed:kCPDarkGradientTheme]];
scatterPlot.paddingLeft = 10.0;
scatterPlot.paddingTop = 10.0;
scatterPlot.paddingRight = 10.0;
scatterPlot.paddingBottom = 10.0;
// Setup plot space
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)scatterPlot.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(1.0) length:CPDecimalFromFloat(2.0)];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(1.0) length:CPDecimalFromFloat(3.0)];
// Axes
CPXYAxisSet *axisSet = (CPXYAxisSet *)scatterPlot.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.majorIntervalLength = CPDecimalFromString(@"0.5");
x.orthogonalCoordinateDecimal = CPDecimalFromString(@"2");
x.minorTicksPerInterval = 2;
NSArray *exclusionRanges = [NSArray arrayWithObjects:
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(1.99) length:CPDecimalFromFloat(0.02)],
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.99) length:CPDecimalFromFloat(0.02)],
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(2.99) length:CPDecimalFromFloat(0.02)],
nil];
x.labelExclusionRanges = exclusionRanges;
CPXYAxis *y = axisSet.yAxis;
y.majorIntervalLength = CPDecimalFromString(@"0.5");
y.minorTicksPerInterval = 5;
y.orthogonalCoordinateDecimal = CPDecimalFromString(@"2");
exclusionRanges = [NSArray arrayWithObjects:
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(1.99) length:CPDecimalFromFloat(0.02)],
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.99) length:CPDecimalFromFloat(0.02)],
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(3.99) length:CPDecimalFromFloat(0.02)],
nil];
y.labelExclusionRanges = exclusionRanges;
// Create a blue plot area
CPScatterPlot *boundLinePlot = [[[CPScatterPlot alloc] init] autorelease];
boundLinePlot.identifier = @"Blue Plot";
CPMutableLineStyle *lineStyle = [[boundLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.miterLimit = 1.0f;
lineStyle.lineWidth = 3.0f;
lineStyle.lineColor = [CPColor blueColor];
boundLinePlot.dataLineStyle = lineStyle;
boundLinePlot.dataSource = self;
[scatterPlot addPlot:boundLinePlot];
// Do a blue gradient
CPColor *areaColor1 = [CPColor colorWithComponentRed:0.3 green:0.3 blue:1.0 alpha:0.8];
CPGradient *areaGradient1 = [CPGradient gradientWithBeginningColor:areaColor1 endingColor:[CPColor clearColor]];
areaGradient1.angle = -90.0f;
CPFill *areaGradientFill = [CPFill fillWithGradient:areaGradient1];
boundLinePlot.areaFill = areaGradientFill;
boundLinePlot.areaBaseValue = [[NSDecimalNumber zero] decimalValue];
// Add plot symbols
CPMutableLineStyle *symbolLineStyle = [CPMutableLineStyle lineStyle];
symbolLineStyle.lineColor = [CPColor blackColor];
CPPlotSymbol *plotSymbol = [CPPlotSymbol ellipsePlotSymbol];
plotSymbol.fill = [CPFill fillWithColor:[CPColor blueColor]];
plotSymbol.lineStyle = symbolLineStyle;
plotSymbol.size = CGSizeMake(10.0, 10.0);
boundLinePlot.plotSymbol = plotSymbol;
// Create a green plot area
CPScatterPlot *dataSourceLinePlot = [[[CPScatterPlot alloc] init] autorelease];
dataSourceLinePlot.identifier = @"Green Plot";
lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.lineWidth = 3.f;
lineStyle.lineColor = [CPColor greenColor];
lineStyle.dashPattern = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:5.0f],
[NSNumber numberWithFloat:5.0f],
nil];
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.dataSource = self;
// Put an area gradient under the plot above
CPColor *areaColor = [CPColor colorWithComponentRed:0.3 green:1.0 blue:0.3 alpha:0.8];
CPGradient *areaGradient = [CPGradient gradientWithBeginningColor:areaColor endingColor:[CPColor clearColor]];
areaGradient.angle = -90.0f;
areaGradientFill = [CPFill fillWithGradient:areaGradient];
dataSourceLinePlot.areaFill = areaGradientFill;
dataSourceLinePlot.areaBaseValue = CPDecimalFromString(@"1.75");
// Animate in the new plot, as an example
dataSourceLinePlot.opacity = 1.0f;
[scatterPlot addPlot:dataSourceLinePlot];
// Add some initial data
NSMutableArray *contentArray = [NSMutableArray arrayWithCapacity:100];
NSUInteger i;
for ( i = 0; i < 60; i++ ) {
id x = [NSNumber numberWithFloat:1+i*0.05];
id y = [NSNumber numberWithFloat:1.2*rand()/(float)RAND_MAX + 1.2];
[contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x, @"x", y, @"y", nil]];
}
self.dataForPlot = contentArray;
}
- (void)renderBarPlotInLayer:(CPGraphHostingView*)layerHostingView withTheme:(CPTheme*)theme
{
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
CGRect bounds = layerHostingView.bounds;
#else
CGRect bounds = NSRectToCGRect(layerHostingView.bounds);
#endif
BOOL drawAxis = YES;
if (bounds.size.width < 200.0f) {
drawAxis = NO;
}
barChart = [[CPXYGraph alloc] initWithFrame:[barChartView bounds]];
[self addGraph:barChart toHostingView:layerHostingView];
[self applyTheme:theme toGraph:barChart withDefault:[CPTheme themeNamed:kCPDarkGradientTheme]];
barChart.plotAreaFrame.masksToBorder = NO;
if (drawAxis) {
barChart.paddingLeft = 70.0;
barChart.paddingTop = 20.0;
barChart.paddingRight = 20.0;
barChart.paddingBottom = 80.0;
}
else {
[self setPaddingDefaultsForGraph:barChart withBounds:bounds];
}
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)barChart.defaultPlotSpace;
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0f) length:CPDecimalFromFloat(300.0f)];
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-1.0f) length:CPDecimalFromFloat(17.0f)];
if (drawAxis) {
CPXYAxisSet *axisSet = (CPXYAxisSet *)barChart.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.axisLineStyle = nil;
x.majorTickLineStyle = nil;
x.minorTickLineStyle = nil;
x.majorIntervalLength = CPDecimalFromString(@"5");
x.orthogonalCoordinateDecimal = CPDecimalFromString(@"0");
x.title = @"X Axis";
x.titleLocation = CPDecimalFromFloat(7.5f);
x.titleOffset = 55.0f;
// Define some custom labels for the data elements
x.labelRotation = M_PI/4;
x.labelingPolicy = CPAxisLabelingPolicyNone;
NSArray *customTickLocations = [NSArray arrayWithObjects:
[NSDecimalNumber numberWithInt:1],
[NSDecimalNumber numberWithInt:5],
[NSDecimalNumber numberWithInt:10],
[NSDecimalNumber numberWithInt:15],
nil];
NSArray *xAxisLabels = [NSArray arrayWithObjects:@"Label A", @"Label B", @"Label C", @"Label D", @"Label E", nil];
NSUInteger labelLocation = 0;
NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:[xAxisLabels count]];
for (NSNumber *tickLocation in customTickLocations) {
CPAxisLabel *newLabel = [[CPAxisLabel alloc] initWithText: [xAxisLabels objectAtIndex:labelLocation++] textStyle:x.labelTextStyle];
newLabel.tickLocation = [tickLocation decimalValue];
newLabel.offset = x.labelOffset + x.majorTickLength;
newLabel.rotation = M_PI/4;
[customLabels addObject:newLabel];
[newLabel release];
}
x.axisLabels = [NSSet setWithArray:customLabels];
CPXYAxis *y = axisSet.yAxis;
y.axisLineStyle = nil;
y.majorTickLineStyle = nil;
y.minorTickLineStyle = nil;
y.majorIntervalLength = CPDecimalFromString(@"50");
y.orthogonalCoordinateDecimal = CPDecimalFromString(@"0");
y.title = @"Y Axis";
y.titleOffset = 45.0f;
y.titleLocation = CPDecimalFromFloat(150.0f);
}
// First bar plot
CPBarPlot *barPlot = [CPBarPlot tubularBarPlotWithColor:[CPColor redColor] horizontalBars:NO];
barPlot.dataSource = self;
barPlot.identifier = @"Bar Plot 1";
[barChart addPlot:barPlot toPlotSpace:plotSpace];
// Second bar plot
barPlot = [CPBarPlot tubularBarPlotWithColor:[CPColor blueColor] horizontalBars:NO];
barPlot.dataSource = self;
barPlot.barOffset = CPDecimalFromFloat(0.25f); // 25% offset, 75% overlap
barPlot.barCornerRadius = 2.0f;
barPlot.identifier = @"Bar Plot 2";
barPlot.delegate = self;
[barChart addPlot:barPlot toPlotSpace:plotSpace];
}
- (void)renderPieChartInLayer:(CPGraphHostingView*)layerHostingView withTheme:(CPTheme*)theme
{
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
CGRect bounds = layerHostingView.bounds;
#else
CGRect bounds = NSRectToCGRect(layerHostingView.bounds);
#endif
pieChart = [[CPXYGraph alloc] initWithFrame:[pieChartView bounds]];
[self addGraph:pieChart toHostingView:layerHostingView];
[self applyTheme:theme toGraph:pieChart withDefault:[CPTheme themeNamed:kCPDarkGradientTheme]];
pieChart.plotAreaFrame.masksToBorder = NO;
[self setPaddingDefaultsForGraph:pieChart withBounds:bounds];
pieChart.axisSet = nil;
// Add pie chart
CPPieChart *piePlot = [[CPPieChart alloc] init];
piePlot.dataSource = self;
piePlot.pieRadius = MIN(0.7 * (layerHostingView.frame.size.height - 2 * pieChart.paddingLeft) / 2.0,
0.7 * (layerHostingView.frame.size.width - 2 * pieChart.paddingTop) / 2.0);
piePlot.identifier = @"Pie Chart 1";
piePlot.startAngle = M_PI_4;
piePlot.sliceDirection = CPPieDirectionCounterClockwise;
piePlot.borderLineStyle = [CPLineStyle lineStyle];
//piePlot.sliceLabelOffset = 5.0;
[pieChart addPlot:piePlot];
[piePlot release];
// Add some initial data
NSMutableArray *contentArray = [NSMutableArray arrayWithObjects:
[NSNumber numberWithDouble:20.0],
[NSNumber numberWithDouble:30.0],
[NSNumber numberWithDouble:60.0],
nil];
self.dataForChart = contentArray;
}
#pragma mark -
#pragma mark CPBarPlot delegate method
-(void)barPlot:(CPBarPlot *)plot barWasSelectedAtRecordIndex:(NSUInteger)index
{
NSLog(@"barWasSelectedAtRecordIndex %d", (int)index);
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
if ([plot isKindOfClass:[CPPieChart class]]) {
return [self.dataForChart count];
}
else if ([plot isKindOfClass:[CPBarPlot class]]) {
return 16;
}
else {
return [dataForPlot count];
}
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSDecimalNumber *num = nil;
if ([plot isKindOfClass:[CPPieChart class]]) {
if (index >= [self.dataForChart count]) return nil;
if (fieldEnum == CPPieChartFieldSliceWidth) {
return [self.dataForChart objectAtIndex:index];
}
else {
return [NSNumber numberWithInt:index];
}
}
else if ([plot isKindOfClass:[CPBarPlot class]]) {
switch (fieldEnum) {
case CPBarPlotFieldBarLocation:
num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:index];
break;
case CPBarPlotFieldBarTip:
num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:(index+1)*(index+1)];
if ( [plot.identifier isEqual:@"Bar Plot 2"] ) {
num = [num decimalNumberBySubtracting:[NSDecimalNumber decimalNumberWithString:@"10"]];
}
break;
}
}
else {
num = [[dataForPlot objectAtIndex:index] valueForKey:(fieldEnum == CPScatterPlotFieldX ? @"x" : @"y")];
// Green plot gets shifted above the blue
if ([(NSString *)plot.identifier isEqualToString:@"Green Plot"])
{
if (fieldEnum == CPScatterPlotFieldY) {
num = (NSDecimalNumber *)[NSDecimalNumber numberWithDouble:[num doubleValue] + 1.0];
}
}
}
return num;
}
-(CPFill *) barFillForBarPlot:(CPBarPlot *)barPlot recordIndex:(NSNumber *)index;
{
return nil;
}
-(CPLayer *)dataLabelForPlot:(CPPlot *)plot recordIndex:(NSUInteger)index
{
static CPMutableTextStyle *whiteText = nil;
if (!whiteText) {
whiteText = [[CPMutableTextStyle alloc] init];
whiteText.color = [CPColor whiteColor];
}
CPTextLayer *newLayer = nil;
switch (index) {
case 0:
newLayer = (id)[NSNull null];
break;
case 1:
newLayer = [[[CPTextLayer alloc] initWithText:[NSString stringWithFormat:@"%lu", index]
style:[CPTextStyle textStyle]] autorelease];
break;
default:
newLayer = [[[CPTextLayer alloc] initWithText:[NSString stringWithFormat:@"%lu", index]
style:whiteText] autorelease];
break;
}
return newLayer;
}
- (void)dealloc
{
[dataForChart release];
[dataForPlot release];
[super dealloc];
}
#if TARGET_OS_IPHONE
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
if (UIInterfaceOrientationIsLandscape(fromInterfaceOrientation))
{
// Move the plots into place for portrait
scatterPlotView.frame = CGRectMake(20.0f, 55.0f, 728.0f, 556.0f);
barChartView.frame = CGRectMake(20.0f, 644.0f, 340.0f, 340.0f);
pieChartView.frame = CGRectMake(408.0f, 644.0f, 340.0f, 340.0f);
}
else
{
// Move the plots into place for landscape
scatterPlotView.frame = CGRectMake(20.0f, 51.0f, 628.0f, 677.0f);
barChartView.frame = CGRectMake(684.0f, 51.0f, 320.0f, 320.0f);
pieChartView.frame = CGRectMake(684.0f, 408.0f, 320.0f, 320.0f);
}
}
#endif
@end
| 08iteng-ipad | examples/CorePlotGallery/src/plots/CompositePlot.m | Objective-C | bsd | 20,447 |
//
// SteppedScatterPlot.m
// Plot Gallery-Mac
//
// Created by Jeff Buck on 11/14/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "SteppedScatterPlot.h"
@implementation SteppedScatterPlot
+ (void)load
{
[super registerPlotItem:self];
}
- (id)init
{
if ((self = [super init])) {
title = @"Stepped Scatter Plot";
}
return self;
}
- (void)generateData
{
if (plotData == nil) {
NSMutableArray *contentArray = [NSMutableArray array];
for (NSUInteger i = 0; i < 10; i++) {
id x = [NSDecimalNumber numberWithDouble:1.0 + i * 0.05];
id y = [NSDecimalNumber numberWithDouble:1.2 * rand()/(double)RAND_MAX + 1.2];
[contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x, @"x", y, @"y", nil]];
}
plotData = [contentArray retain];
}
}
- (void)renderInLayer:(CPGraphHostingView *)layerHostingView withTheme:(CPTheme *)theme
{
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
CGRect bounds = layerHostingView.bounds;
#else
CGRect bounds = NSRectToCGRect(layerHostingView.bounds);
#endif
CPGraph* graph = [[[CPXYGraph alloc] initWithFrame:[layerHostingView bounds]] autorelease];
[self addGraph:graph toHostingView:layerHostingView];
[self applyTheme:theme toGraph:graph withDefault:[CPTheme themeNamed:kCPSlateTheme]];
[self setTitleDefaultsForGraph:graph withBounds:bounds];
[self setPaddingDefaultsForGraph:graph withBounds:bounds];
CPScatterPlot *dataSourceLinePlot = [[[CPScatterPlot alloc] init] autorelease];
dataSourceLinePlot.cachePrecision = CPPlotCachePrecisionDouble;
CPMutableLineStyle *lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.lineWidth = 1.0;
lineStyle.lineColor = [CPColor greenColor];
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.dataSource = self;
CPMutableTextStyle *whiteTextStyle = [CPMutableTextStyle textStyle];
whiteTextStyle.color = [CPColor whiteColor];
dataSourceLinePlot.labelTextStyle = whiteTextStyle;
dataSourceLinePlot.labelOffset = 5.0;
dataSourceLinePlot.labelRotation = M_PI_4;
[graph addPlot:dataSourceLinePlot];
// Make the data source line use stepped interpolation
dataSourceLinePlot.interpolation = CPScatterPlotInterpolationStepped;
// Put an area gradient under the plot above
CPColor *areaColor = [CPColor colorWithComponentRed:0.3 green:1.0 blue:0.3 alpha:0.8];
CPGradient *areaGradient = [CPGradient gradientWithBeginningColor:areaColor endingColor:[CPColor clearColor]];
areaGradient.angle = -90.0;
CPFill *areaGradientFill = [CPFill fillWithGradient:areaGradient];
dataSourceLinePlot.areaFill = areaGradientFill;
dataSourceLinePlot.areaBaseValue = CPDecimalFromString(@"1.75");
[self generateData];
// Auto scale the plot space to fit the plot data
// Extend the y range by 10% for neatness
CPXYPlotSpace *plotSpace = (id)graph.defaultPlotSpace;
[plotSpace scaleToFitPlots:[NSArray arrayWithObjects:dataSourceLinePlot, nil]];
CPPlotRange *xRange = plotSpace.xRange;
CPPlotRange *yRange = plotSpace.yRange;
[yRange expandRangeByFactor:CPDecimalFromDouble(1.1)];
plotSpace.yRange = yRange;
// Restrict y range to a global range
CPPlotRange *globalYRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0f) length:CPDecimalFromFloat(6.0f)];
plotSpace.globalYRange = globalYRange;
// set the x and y shift to match the new ranges
CGFloat length = xRange.lengthDouble;
xShift = length - 3.0;
length = yRange.lengthDouble;
yShift = length - 2.0;
}
- (void)dealloc
{
[plotData release];
[super dealloc];
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
return [plotData count];
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSNumber* num = [[plotData objectAtIndex:index] valueForKey:(fieldEnum == CPScatterPlotFieldX ? @"x" : @"y")];
if (fieldEnum == CPScatterPlotFieldY) {
num = [NSNumber numberWithDouble:[num doubleValue]];
}
return num;
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/plots/SteppedScatterPlot.m | Objective-C | bsd | 4,260 |
//
// PlotGallery.m
// CorePlotGallery
//
// Created by Jeff Buck on 7/31/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "PlotGallery.h"
@implementation PlotGallery
static PlotGallery *sharedPlotGallery = nil;
+ (PlotGallery *)sharedPlotGallery
{
@synchronized(self) {
if (sharedPlotGallery == nil) {
sharedPlotGallery = [[self alloc] init];
}
}
return sharedPlotGallery;
}
+ (id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
if (sharedPlotGallery == nil) {
return[super allocWithZone:zone];
}
}
return sharedPlotGallery;
}
- (id)init
{
Class thisClass = [self class];
@synchronized(thisClass) {
if (sharedPlotGallery == nil) {
if ((self = [super init])) {
sharedPlotGallery = self;
plotItems = [[NSMutableArray alloc] init];
}
}
}
return sharedPlotGallery;
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (NSUInteger)retainCount
{
return UINT_MAX;
}
- (void)release
{
}
- (id)autorelease
{
return self;
}
- (void)addPlotItem:(PlotItem *)plotItem
{
[plotItems addObject:plotItem];
}
- (int)count
{
return [plotItems count];
}
- (PlotItem *)objectAtIndex:(int)index
{
return [plotItems objectAtIndex:index];
}
- (void)sortByTitle
{
[plotItems sortUsingSelector:@selector(titleCompare:)];
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/shared/PlotGallery.m | Objective-C | bsd | 1,477 |
//
// PlotItem.m
// CorePlotGallery
//
// Created by Jeff Buck on 9/4/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "PlotGallery.h"
#import "PlotItem.h"
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
#else
// For IKImageBrowser
#import <Quartz/Quartz.h>
#endif
@implementation PlotItem
@synthesize defaultLayerHostingView;
@synthesize graphs;
@synthesize title;
+ (void)registerPlotItem:(id)item
{
NSLog(@"registerPlotItem for class %@", [item class]);
Class itemClass = [item class];
if (itemClass) {
// There's no autorelease pool here yet...
PlotItem *plotItem = [[itemClass alloc] init];
if (plotItem) {
[[PlotGallery sharedPlotGallery] addPlotItem:plotItem];
[plotItem release];
}
}
}
- (id)init
{
if ((self = [super init])) {
graphs = [[NSMutableArray alloc] init];
}
return self;
}
- (void)addGraph:(CPGraph *)graph toHostingView:(CPGraphHostingView *)layerHostingView
{
[graphs addObject:graph];
if (layerHostingView) {
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
layerHostingView.hostedGraph = graph;
#else
layerHostingView.hostedLayer = graph;
#endif
}
}
- (void)addGraph:(CPGraph *)graph
{
[self addGraph:graph toHostingView:nil];
}
- (void)killGraph
{
// Remove the CPLayerHostingView
if (defaultLayerHostingView) {
[defaultLayerHostingView removeFromSuperview];
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
defaultLayerHostingView.hostedGraph = nil;
#else
defaultLayerHostingView.hostedLayer = nil;
#endif
[defaultLayerHostingView release];
defaultLayerHostingView = nil;
}
[cachedImage release];
cachedImage = nil;
[graphs removeAllObjects];
}
- (void)dealloc
{
[self killGraph];
[super dealloc];
}
- (NSComparisonResult)titleCompare:(PlotItem *)other
{
return [title caseInsensitiveCompare:other.title];
}
- (void)setTitleDefaultsForGraph:(CPGraph *)graph withBounds:(CGRect)bounds
{
graph.title = title;
CPMutableTextStyle *textStyle = [CPMutableTextStyle textStyle];
textStyle.color = [CPColor grayColor];
textStyle.fontName = @"Helvetica-Bold";
textStyle.fontSize = round(bounds.size.height / 20.0f);
graph.titleTextStyle = textStyle;
graph.titleDisplacement = CGPointMake(0.0f, round(bounds.size.height / 18.0f)); // Ensure that title displacement falls on an integral pixel
graph.titlePlotAreaFrameAnchor = CPRectAnchorTop;
}
- (void)setPaddingDefaultsForGraph:(CPGraph *)graph withBounds:(CGRect)bounds
{
float boundsPadding = round(bounds.size.width / 20.0f); // Ensure that padding falls on an integral pixel
graph.paddingLeft = boundsPadding;
if (graph.titleDisplacement.y > 0.0) {
graph.paddingTop = graph.titleDisplacement.y * 2;
}
else {
graph.paddingTop = boundsPadding;
}
graph.paddingRight = boundsPadding;
graph.paddingBottom = boundsPadding;
}
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
// There's a UIImage function to scale and orient an existing image,
// but this will also work in pre-4.0 iOS
- (CGImageRef)scaleCGImage:(CGImageRef)image toSize:(CGSize)size
{
CGColorSpaceRef colorspace = CGImageGetColorSpace(image);
CGContextRef c = CGBitmapContextCreate(NULL,
size.width,
size.height,
CGImageGetBitsPerComponent(image),
CGImageGetBytesPerRow(image),
colorspace,
CGImageGetAlphaInfo(image));
CGColorSpaceRelease(colorspace);
if (c == NULL) {
return nil;
}
CGContextDrawImage(c, CGRectMake(0, 0, size.width, size.height), image);
CGImageRef newImage = CGBitmapContextCreateImage(c);
CGContextRelease(c);
return newImage;
}
- (UIImage *)image
{
if (cachedImage == nil) {
CGRect imageFrame = CGRectMake(0, 0, 100, 75);
UIView *imageView = [[UIView alloc] initWithFrame:imageFrame];
[imageView setOpaque:YES];
[imageView setUserInteractionEnabled:NO];
[self renderInView:imageView withTheme:nil];
[self reloadData];
UIGraphicsBeginImageContext(imageView.bounds.size);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextGetCTM(c);
CGContextScaleCTM(c, 1, -1);
CGContextTranslateCTM(c, 0, -imageView.bounds.size.height);
[imageView.layer renderInContext:c];
cachedImage = [UIGraphicsGetImageFromCurrentImageContext() retain];
// This code was to rescale a graph that needed a larger rendering
// area because of absolute pixel sizing. All of the sample plots
// are now aware of device/screen sizes and should render properly
// even to a thumbnail size.
//UIImage* bigImage = UIGraphicsGetImageFromCurrentImageContext();
//cachedImage = [[UIImage imageWithCGImage:[self scaleCGImage:[bigImage CGImage] toSize:CGSizeMake(100.0f, 75.0f)]] retain];
UIGraphicsEndImageContext();
[imageView release];
}
return cachedImage;
}
#else // OSX
- (NSImage *)image
{
if (cachedImage == nil) {
CGRect imageFrame = CGRectMake(0, 0, 400, 300);
NSView *imageView = [[NSView alloc] initWithFrame:NSRectFromCGRect(imageFrame)];
[imageView setWantsLayer:YES];
[self renderInView:imageView withTheme:nil];
[self reloadData];
CGSize boundsSize = imageFrame.size;
NSBitmapImageRep *layerImage = [[NSBitmapImageRep alloc]
initWithBitmapDataPlanes:NULL
pixelsWide:boundsSize.width
pixelsHigh:boundsSize.height
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSCalibratedRGBColorSpace
bytesPerRow:(NSInteger)boundsSize.width * 4
bitsPerPixel:32];
NSGraphicsContext *bitmapContext = [NSGraphicsContext graphicsContextWithBitmapImageRep:layerImage];
CGContextRef context = (CGContextRef)[bitmapContext graphicsPort];
CGContextClearRect(context, CGRectMake(0.0, 0.0, boundsSize.width, boundsSize.height));
CGContextSetAllowsAntialiasing(context, true);
CGContextSetShouldSmoothFonts(context, false);
[imageView.layer renderInContext:context];
CGContextFlush(context);
cachedImage = [[NSImage alloc] initWithSize:NSSizeFromCGSize(boundsSize)];
[cachedImage addRepresentation:layerImage];
[layerImage release];
[imageView release];
}
return cachedImage;
}
#endif
- (void)applyTheme:(CPTheme *)theme toGraph:(CPGraph *)graph withDefault:(CPTheme *)defaultTheme
{
if (theme == nil) {
[graph applyTheme:defaultTheme];
}
else if (![theme isKindOfClass:[NSNull class]]) {
[graph applyTheme:theme];
}
}
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
#else
- (void)setFrameSize:(NSSize)size
{
}
#endif
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
- (void)renderInView:(UIView*)hostingView withTheme:(CPTheme*)theme
#else
- (void)renderInView:(NSView*)hostingView withTheme:(CPTheme*)theme
#endif
{
[self killGraph];
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
CGRect bounds = [hostingView bounds];
#else
CGRect bounds = NSRectToCGRect([hostingView bounds]);
#endif
defaultLayerHostingView = [[CPGraphHostingView alloc] initWithFrame:bounds];
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
defaultLayerHostingView.collapsesLayers = NO;
#else
[defaultLayerHostingView setAutoresizesSubviews:YES];
[defaultLayerHostingView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
#endif
[hostingView addSubview:defaultLayerHostingView];
[self renderInLayer:defaultLayerHostingView withTheme:theme];
}
- (void)renderInLayer:(CPGraphHostingView *)layerHostingView withTheme:(CPTheme *)theme
{
NSLog(@"PlotItem:renderInLayer: Override me");
}
- (void)reloadData
{
for (CPGraph *g in graphs) {
[g reloadData];
}
}
#pragma mark -
#pragma mark IKImageBrowserItem methods
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
#else
- (NSString *)imageUID
{
return title;
}
- (NSString *)imageRepresentationType
{
return IKImageBrowserNSImageRepresentationType;
}
- (id)imageRepresentation
{
return [self image];
}
- (NSString *)imageTitle
{
return title;
}
/*
- (NSString*)imageSubtitle
{
return graph.title;
}
*/
#endif
@end
| 08iteng-ipad | examples/CorePlotGallery/src/shared/PlotItem.m | Objective-C | bsd | 9,051 |
//
// PlotItem.h
// CorePlotGallery
//
// Created by Jeff Buck on 8/31/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import <Foundation/Foundation.h>
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#import "CorePlot-CocoaTouch.h"
typedef CGRect CGNSRect;
#else
#import <CorePlot/CorePlot.h>
typedef CPLayerHostingView CPGraphHostingView;
typedef NSRect CGNSRect;
#endif
@class CPGraph;
@class CPTheme;
@interface PlotItem : NSObject
{
CPGraphHostingView *defaultLayerHostingView;
NSMutableArray *graphs;
NSString *title;
CPNativeImage *cachedImage;
}
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
@property (nonatomic, retain) CPGraphHostingView *defaultLayerHostingView;
#else
@property (nonatomic, retain) CPLayerHostingView *defaultLayerHostingView;
#endif
@property (nonatomic, retain) NSMutableArray *graphs;
@property (nonatomic, retain) NSString *title;
+ (void)registerPlotItem:(id)item;
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
- (void)renderInView:(UIView *)hostingView withTheme:(CPTheme *)theme;
#else
- (void)renderInView:(NSView *)hostingView withTheme:(CPTheme *)theme;
- (void)setFrameSize:(NSSize)size;
#endif
- (CPNativeImage *)image;
- (void)renderInLayer:(CPGraphHostingView *)layerHostingView withTheme:(CPTheme *)theme;
- (void)setTitleDefaultsForGraph:(CPGraph *)graph withBounds:(CGRect)bounds;
- (void)setPaddingDefaultsForGraph:(CPGraph *)graph withBounds:(CGRect)bounds;
- (void)reloadData;
- (void)applyTheme:(CPTheme *)theme toGraph:(CPGraph *)graph withDefault:(CPTheme *)defaultTheme;
- (void)addGraph:(CPGraph *)graph;
- (void)addGraph:(CPGraph *)graph toHostingView:(CPGraphHostingView *)layerHostingView;
- (void)killGraph;
- (NSComparisonResult)titleCompare:(PlotItem *)other;
@end
| 08iteng-ipad | examples/CorePlotGallery/src/shared/PlotItem.h | Objective-C | bsd | 1,826 |
//
// PlotGallery.h
// CorePlotGallery
//
// Created by Jeff Buck on 7/31/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "PlotItem.h"
@interface PlotGallery : NSObject
{
NSMutableArray *plotItems;
}
+ (PlotGallery *)sharedPlotGallery;
- (void)addPlotItem:(PlotItem *)plotItem;
- (void)sortByTitle;
- (int)count;
- (PlotItem *)objectAtIndex:(int)index;
@end
| 08iteng-ipad | examples/CorePlotGallery/src/shared/PlotGallery.h | Objective-C | bsd | 389 |
//
// RootViewController.h
// CorePlotGallery
//
// Created by Jeff Buck on 8/28/10.
// Copyright Jeff Buck 2010. All rights reserved.
//
#import <UIKit/UIKit.h>
@class DetailViewController;
@interface RootViewController : UITableViewController
{
DetailViewController *detailViewController;
}
@property (nonatomic, retain) IBOutlet DetailViewController *detailViewController;
@end
| 08iteng-ipad | examples/CorePlotGallery/src/ios/RootViewController.h | Objective-C | bsd | 397 |
//
// PlotGalleryAppDelegate-iPhone.h
// Plot Gallery-iOS
//
// Created by Jeff Buck on 10/17/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface PlotGalleryAppDelegate_iPhone : NSObject <UIApplicationDelegate>
{
UIWindow *window;
UINavigationController *navigationController;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
@end
| 08iteng-ipad | examples/CorePlotGallery/src/ios/iphone/PlotGalleryAppDelegate-iPhone.h | Objective-C | bsd | 493 |
//
// PlotGalleryAppDelegate-iPhone.m
// Plot Gallery-iOS
//
// Created by Jeff Buck on 10/17/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "PlotGalleryAppDelegate-iPhone.h"
#import "PlotGallery.h"
@implementation PlotGalleryAppDelegate_iPhone
@synthesize window;
@synthesize navigationController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[PlotGallery sharedPlotGallery] sortByTitle];
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];
return YES;
}
- (void)applicationWillTerminate:(UIApplication *)application
{
}
- (void)dealloc
{
[navigationController release];
[window release];
[super dealloc];
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/ios/iphone/PlotGalleryAppDelegate-iPhone.m | Objective-C | bsd | 748 |
//
// PlotHostView.m
// Plot Gallery
//
// Created by Jeff Buck on 9/4/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "PlotHostView.h"
@implementation PlotHostView
- (id)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame]))
{
}
return self;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
NSLog(@"PlotHostView:didRotateFromInterfaceOrientation:");
}
- (void)dealloc
{
[super dealloc];
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/ios/PlotHostView.m | Objective-C | bsd | 620 |
//
// RootViewController.m
// CorePlotGallery
//
// Created by Jeff Buck on 8/28/10.
// Copyright Jeff Buck 2010. All rights reserved.
//
#import "RootViewController.h"
#import "DetailViewController.h"
#import "PlotGallery.h"
#import "PlotItem.h"
@implementation RootViewController
@synthesize detailViewController;
- (void)viewDidLoad
{
[super viewDidLoad];
self.clearsSelectionOnViewWillAppear = NO;
self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tv
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tv numberOfRowsInSection:(NSInteger)section
{
return [[PlotGallery sharedPlotGallery] count];
}
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId = @"PlotCell";
UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:cellId];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId] autorelease];
cell.accessoryType = UITableViewCellAccessoryNone;
}
PlotItem *plotItem = [[PlotGallery sharedPlotGallery] objectAtIndex:indexPath.row];
cell.imageView.image = [plotItem image];
cell.textLabel.text = plotItem.title;
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
PlotItem *plotItem = [[PlotGallery sharedPlotGallery] objectAtIndex:indexPath.row];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
detailViewController.detailItem = plotItem;
}
else {
detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:nil];
[self.navigationController pushViewController:detailViewController animated:YES];
detailViewController.detailItem = plotItem;
[detailViewController release];
detailViewController = nil;
}
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload
{
detailViewController = nil;
}
- (void)dealloc
{
[detailViewController release];
detailViewController = nil;
[super dealloc];
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/ios/RootViewController.m | Objective-C | bsd | 2,476 |
//
// main.m
// CorePlotGallery
//
// Created by Jeff Buck on 8/28/10.
// Copyright Jeff Buck 2010. All rights reserved.
//
#import <UIKit/UIKit.h>
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
| 08iteng-ipad | examples/CorePlotGallery/src/ios/main.m | Objective-C | bsd | 352 |
//
// ThemeTableViewController.m
// CorePlotGallery
//
// Created by Jeff Buck on 8/31/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import "ThemeTableViewController.h"
#import "CorePlot-CocoaTouch.h"
@implementation ThemeTableViewController
@synthesize themePopoverController;
@synthesize delegate;
- (void)setupThemes
{
themes = [[NSMutableArray alloc] init];
[themes addObject:kThemeTableViewControllerDefaultTheme];
[themes addObject:kThemeTableViewControllerNoTheme];
for (Class c in [CPTheme themeClasses]) {
[themes addObject:[c defaultName]];
}
}
- (void)awakeFromNib
{
[self setupThemes];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])
{
[self setupThemes];
}
return self;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [themes count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"ThemeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [themes objectAtIndex:indexPath.row];
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[delegate themeSelectedAtIndex:[themes objectAtIndex:indexPath.row]];
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload
{
}
- (void)dealloc
{
[self.tableView setDataSource:nil];
[self.tableView setDelegate:nil];
[delegate release];
[themes release];
[super dealloc];
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/ios/ThemeTableViewController.m | Objective-C | bsd | 2,330 |
//
// DetailViewController.h
// CorePlotGallery
//
// Created by Jeff Buck on 8/28/10.
// Copyright Jeff Buck 2010. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "CorePlot-CocoaTouch.h"
#import "ThemeTableViewController.h"
#import "PlotItem.h"
@interface DetailViewController : UIViewController <UIPopoverControllerDelegate,
UISplitViewControllerDelegate,
ThemeTableViewControllerDelegate>
{
UIPopoverController *popoverController;
UIToolbar *toolbar;
PlotItem *detailItem;
UIView *hostingView;
UIBarButtonItem *themeBarButton;
UIPopoverController *themePopoverController;
ThemeTableViewController *themeTableViewController;
NSString *currentThemeName;
}
@property (nonatomic, retain) IBOutlet UIToolbar *toolbar;
@property (nonatomic, retain) PlotItem *detailItem;
@property (nonatomic, retain) IBOutlet UIView *hostingView;
@property (nonatomic, retain) IBOutlet UIBarButtonItem *themeBarButton;
@property (nonatomic, retain) IBOutlet ThemeTableViewController *themeTableViewController;
@property (nonatomic, copy) NSString *currentThemeName;
- (IBAction)showThemes:(id)sender;
@end
| 08iteng-ipad | examples/CorePlotGallery/src/ios/DetailViewController.h | Objective-C | bsd | 1,352 |
//
// PlotHostView.h
// Plot Gallery
//
// Created by Jeff Buck on 9/4/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface PlotHostView : UIView
{
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/ios/PlotHostView.h | Objective-C | bsd | 203 |
//
// ThemeTableViewController.h
// CorePlotGallery
//
// Created by Jeff Buck on 8/31/10.
// Copyright 2010 Jeff Buck. All rights reserved.
//
#import <UIKit/UIKit.h>
#define kThemeTableViewControllerNoTheme @"None"
#define kThemeTableViewControllerDefaultTheme @"Default"
@protocol ThemeTableViewControllerDelegate <NSObject>
- (void)themeSelectedAtIndex:(NSString*)themeName;
@end
@interface ThemeTableViewController : UITableViewController
{
UIPopoverController *themePopoverController;
id<ThemeTableViewControllerDelegate> delegate;
NSMutableArray *themes;
}
@property (nonatomic, retain) UIPopoverController *themePopoverController;
@property (nonatomic, retain) id<ThemeTableViewControllerDelegate> delegate;
@end
| 08iteng-ipad | examples/CorePlotGallery/src/ios/ThemeTableViewController.h | Objective-C | bsd | 794 |
//
// DetailViewController.m
// CorePlotGallery
//
// Created by Jeff Buck on 8/28/10.
// Copyright Jeff Buck 2010. All rights reserved.
//
#import "DetailViewController.h"
#import "RootViewController.h"
#import "ThemeTableViewController.h"
@interface DetailViewController ()
@property (nonatomic, retain) UIPopoverController *popoverController;
- (CPTheme *)currentTheme;
@end
@implementation DetailViewController
@synthesize toolbar;
@synthesize popoverController;
@dynamic detailItem;
@synthesize hostingView;
@synthesize themeBarButton;
@synthesize themeTableViewController;
@synthesize currentThemeName;
#pragma mark -
#pragma mark Initialization and Memory Management
- (void)setupView
{
NSString* themeString = [NSString stringWithFormat:@"Theme: %@", kThemeTableViewControllerDefaultTheme];
if (UI_USER_INTERFACE_IDIOM() != UIUserInterfaceIdiomPad) {
themeBarButton = [[UIBarButtonItem alloc] initWithTitle:themeString style:UIBarButtonItemStylePlain target:self action:@selector(showThemes:)];
[[self navigationItem] setRightBarButtonItem:themeBarButton];
}
self.currentThemeName = [NSString stringWithFormat:@"Theme: %@", kThemeTableViewControllerDefaultTheme];
}
- (void)awakeFromNib
{
[self setupView];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
[self setupView];
}
return self;
}
- (void)dealloc
{
[popoverController release];
[toolbar release];
[detailItem release];
[hostingView release];
[themeBarButton release];
[super dealloc];
}
#pragma mark -
#pragma mark Managing the detail item
- (PlotItem *)detailItem
{
return detailItem;
}
- (void)setDetailItem:(id)newDetailItem
{
if (detailItem != newDetailItem) {
[detailItem killGraph];
[detailItem release];
detailItem = [newDetailItem retain];
[detailItem renderInView:hostingView withTheme:[self currentTheme]];
}
if (popoverController != nil) {
[popoverController dismissPopoverAnimated:YES];
}
}
#pragma mark -
#pragma mark Split view support
- (void)splitViewController:(UISplitViewController *)svc
willHideViewController:(UIViewController *)aViewController
withBarButtonItem:(UIBarButtonItem *)barButtonItem
forPopoverController:(UIPopoverController *)pc
{
barButtonItem.title = @"Plot Gallery";
NSMutableArray *items = [[toolbar items] mutableCopy];
[items insertObject:barButtonItem atIndex:0];
[toolbar setItems:items animated:YES];
[items release];
self.popoverController = pc;
}
- (void)splitViewController:(UISplitViewController *)svc
willShowViewController:(UIViewController *)aViewController
invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem
{
NSMutableArray *items = [[toolbar items] mutableCopy];
[items removeObjectAtIndex:0];
[toolbar setItems:items animated:YES];
[items release];
self.popoverController = nil;
}
#pragma mark -
#pragma mark Rotation support
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
[detailItem renderInView:hostingView withTheme:[self currentTheme]];
}
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidAppear:(BOOL)animated
{
themeBarButton.title = currentThemeName;
}
- (void)viewDidUnload
{
self.popoverController = nil;
self.themeBarButton = nil;
}
#pragma mark -
#pragma mark Theme Selection
- (CPTheme *)currentTheme
{
CPTheme *theme;
if (currentThemeName == kThemeTableViewControllerNoTheme) {
theme = (id)[NSNull null];
}
else if (currentThemeName == kThemeTableViewControllerDefaultTheme) {
theme = nil;
}
else {
theme = [CPTheme themeNamed:currentThemeName];
}
return theme;
}
- (void)closeThemePopover
{
// Cancel the popover
[themePopoverController dismissPopoverAnimated:YES];
[themePopoverController release];
themePopoverController = nil;
}
- (IBAction)showThemes:(id)sender
{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
if (themePopoverController == nil) {
themePopoverController = [[UIPopoverController alloc] initWithContentViewController:themeTableViewController];
[themeTableViewController setThemePopoverController:themePopoverController];
[themePopoverController setPopoverContentSize:CGSizeMake(320, 320)];
[themePopoverController presentPopoverFromBarButtonItem:themeBarButton
permittedArrowDirections:UIPopoverArrowDirectionAny
animated:YES];
}
else {
[self closeThemePopover];
}
}
else {
themeTableViewController = [[ThemeTableViewController alloc] initWithNibName:@"ThemeTableViewController" bundle:nil];
[self.navigationController pushViewController:themeTableViewController animated:YES];
themeTableViewController.delegate = self;
}
}
- (void)themeSelectedAtIndex:(NSString *)themeName
{
themeBarButton.title = [NSString stringWithFormat:@"Theme: %@", themeName];
self.currentThemeName = themeName;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
[self closeThemePopover];
}
else {
[self.navigationController popViewControllerAnimated:YES];
themeTableViewController.delegate = nil;
[themeTableViewController release];
themeTableViewController = nil;
}
[detailItem renderInView:hostingView withTheme:[self currentTheme]];
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/ios/DetailViewController.m | Objective-C | bsd | 5,844 |
//
// Plot_GalleryAppDelegate.h
// CorePlotGallery
//
// Created by Jeff Buck on 8/28/10.
// Copyright Jeff Buck 2010. All rights reserved.
//
#import <UIKit/UIKit.h>
@class RootViewController;
@class DetailViewController;
@interface Plot_GalleryAppDelegate : NSObject <UIApplicationDelegate>
{
UIWindow *window;
UISplitViewController *splitViewController;
RootViewController *rootViewController;
DetailViewController *detailViewController;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UISplitViewController *splitViewController;
@property (nonatomic, retain) IBOutlet RootViewController *rootViewController;
@property (nonatomic, retain) IBOutlet DetailViewController *detailViewController;
@end
| 08iteng-ipad | examples/CorePlotGallery/src/ios/ipad/Plot_GalleryAppDelegate.h | Objective-C | bsd | 803 |
//
// Plot_GalleryAppDelegate.m
// CorePlotGallery
//
// Created by Jeff Buck on 8/28/10.
// Copyright Jeff Buck 2010. All rights reserved.
//
#import "Plot_GalleryAppDelegate.h"
#import "RootViewController.h"
#import "DetailViewController.h"
#import "PlotGallery.h"
#import "PlotItem.h"
/*
// Add new PlotItems to this list
static NSString *plotClasses[] =
{
@"SimpleScatterPlot",
@"GradientScatterPlot",
@"SimplePieChart",
@"VerticalBarChart",
@"CompositePlot"
};
*/
@implementation Plot_GalleryAppDelegate
@synthesize window;
@synthesize splitViewController;
@synthesize rootViewController;
@synthesize detailViewController;
#pragma mark -
#pragma mark Application lifecycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
/*
PlotGallery *gallery = [PlotGallery sharedPlotGallery];
int plotCount = sizeof(plotClasses)/sizeof(NSString *);
for (int i = 0; i < plotCount; i++) {
Class plotClass = NSClassFromString(plotClasses[i]);
id plotItem = [[[plotClass alloc] init] autorelease];
if (plotItem) {
[gallery addPlotItem:plotItem];
}
}
*/
[[PlotGallery sharedPlotGallery] sortByTitle];
[window addSubview:splitViewController.view];
[window makeKeyAndVisible];
return YES;
}
#pragma mark -
#pragma mark Memory management
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
NSLog(@"AppDelegate:applicationDidReceiveMemoryWarning");
}
- (void)dealloc
{
[splitViewController release];
[window release];
[super dealloc];
}
@end
| 08iteng-ipad | examples/CorePlotGallery/src/ios/ipad/Plot_GalleryAppDelegate.m | Objective-C | bsd | 1,631 |
{\rtf0\ansi{\fonttbl\f0\fswiss Helvetica;}
{\colortbl;\red255\green255\blue255;}
\paperw9840\paperh8400
\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\ql\qnatural
\f0\b\fs24 \cf0 Engineering:
\b0 \
Some people\
\
\b Human Interface Design:
\b0 \
Some other people\
\
\b Testing:
\b0 \
Hopefully not nobody\
\
\b Documentation:
\b0 \
Whoever\
\
\b With special thanks to:
\b0 \
Mom\
}
| 08iteng-ipad | examples/DropPlot/English.lproj/Credits.rtf | Rich Text Format | bsd | 436 |
//
// main.m
// DropPlot
//
// Created by Brad Larson on 6/9/2009.
// Copyright SonoPlot, Inc. 2009 . All rights reserved.
//
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **) argv);
}
| 08iteng-ipad | examples/DropPlot/main.m | Objective-C | bsd | 251 |
#import <Cocoa/Cocoa.h>
@interface NSString (ParseCSV)
- (NSArray *)arrayByParsingCSVLine;
@end
| 08iteng-ipad | examples/DropPlot/NSString+ParseCSV.h | Objective-C | bsd | 101 |
#import "NSString+ParseCSV.h"
@implementation NSString (ParseCSV)
- (NSArray *)arrayByParsingCSVLine;
{
BOOL isRemoveWhitespace = YES;
NSMutableArray* theArray = [NSMutableArray array];
NSArray* theFields = [self componentsSeparatedByString:@","];
NSCharacterSet* quotedCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"\""];
BOOL inField = NO;
NSMutableString* theConcatenatedField = [NSMutableString string];
unsigned int i;
for(i = 0; i < [theFields count]; i++) {
NSString* theField = [theFields objectAtIndex:i];
switch(inField) {
case NO:
if([theField hasPrefix:@"\""] == YES && [theField hasSuffix:@"\""] == NO) {
inField = YES;
[theConcatenatedField appendString:theField];
[theConcatenatedField appendString:@","];
} else {
if(isRemoveWhitespace) {
[theArray addObject:[theField stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
} else {
[theArray addObject:theField];
}
}
break;
case YES:
[theConcatenatedField appendString:theField];
if([theField hasSuffix:@"\""] == YES) {
NSString* theField = [theConcatenatedField stringByTrimmingCharactersInSet:quotedCharacterSet];
if(isRemoveWhitespace) {
[theArray addObject:[theField stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
} else {
[theArray addObject:theField];
}
[theConcatenatedField setString:@""];
inField = NO;
} else {
[theConcatenatedField appendString:@","];
}
break;
}
}
return theArray;
// TODO: Check this for potential memory leaks, not sure that the array is autoreleased
}
@end
| 08iteng-ipad | examples/DropPlot/NSString+ParseCSV.m | Objective-C | bsd | 1,745 |
#import <Cocoa/Cocoa.h>
#import <CorePlot/CorePlot.h>
@interface CPPlotDocument : NSDocument <CPPlotDataSource>
{
IBOutlet CPLayerHostingView *graphView;
CPXYGraph *graph;
double minimumValueForXAxis, maximumValueForXAxis, minimumValueForYAxis, maximumValueForYAxis;
double majorIntervalLengthForX, majorIntervalLengthForY;
NSMutableArray *dataPoints;
}
// PDF / image export
-(IBAction)exportToPDF:(id)sender;
-(IBAction)exportToPNG:(id)sender;
@end
| 08iteng-ipad | examples/DropPlot/CPPlotDocument.h | Objective-C | bsd | 464 |
#import "CPPlotDocument.h"
#import "NSString+ParseCSV.h"
@implementation CPPlotDocument
//#define USE_NSDECIMAL
+(void)initialize {
[NSValueTransformer setValueTransformer:[CPDecimalNumberValueTransformer new] forName:@"CPDecimalNumberValueTransformer"];
}
- (id)init
{
self = [super init];
if (self) {
dataPoints = [[NSMutableArray alloc] init];
}
return self;
}
-(void)dealloc
{
[graph release];
[dataPoints release];
[super dealloc];
}
- (NSString *)windowNibName
{
return @"CPPlotDocument";
}
- (void)windowControllerDidLoadNib:(NSWindowController *)windowController
{
// Create graph from theme
graph = [(CPXYGraph *)[CPXYGraph alloc] initWithFrame:CGRectZero];
CPTheme *theme = [CPTheme themeNamed:kCPPlainWhiteTheme];
[graph applyTheme:theme];
graphView.hostedLayer = graph;
graph.paddingTop = 40.0;
graph.paddingRight = 40.0;
graph.paddingBottom = 40.0;
// Setup plot space
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(minimumValueForXAxis) length:CPDecimalFromFloat(maximumValueForXAxis - minimumValueForXAxis)];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(minimumValueForYAxis) length:CPDecimalFromFloat(maximumValueForYAxis - minimumValueForYAxis)];
CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.majorIntervalLength = CPDecimalFromDouble(majorIntervalLengthForX);
x.orthogonalCoordinateDecimal = CPDecimalFromDouble(minimumValueForYAxis);
x.minorTicksPerInterval = 5;
CPXYAxis *y = axisSet.yAxis;
y.majorIntervalLength = CPDecimalFromDouble(majorIntervalLengthForY);
y.minorTicksPerInterval = 5;
y.orthogonalCoordinateDecimal = CPDecimalFromDouble(minimumValueForXAxis);
CPMutableLineStyle *borderLineStyle = [CPMutableLineStyle lineStyle];
borderLineStyle.lineColor = [CPColor colorWithGenericGray:0.2];
borderLineStyle.lineWidth = 0.0f;
// CPBorderedLayer *borderedLayer = (CPBorderedLayer *)axisSet.overlayLayer;
// borderedLayer.borderLineStyle = borderLineStyle;
// borderedLayer.cornerRadius = 0.0f;
// Create the main plot for the delimited data
CPScatterPlot *dataSourceLinePlot = [[(CPScatterPlot *)[CPScatterPlot alloc] initWithFrame:graph.bounds] autorelease];
dataSourceLinePlot.identifier = @"Data Source Plot";
CPMutableLineStyle *lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.lineWidth = 1.f;
lineStyle.lineColor = [CPColor blackColor];
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.dataSource = self;
[graph addPlot:dataSourceLinePlot];
// Add plot symbols
// CPLineStyle *symbolLineStyle = [CPLineStyle lineStyle];
// symbolLineStyle.lineColor = [CPColor whiteColor];
// CPPlotSymbol *plotSymbol = [CPPlotSymbol ellipsePlotSymbol];
// plotSymbol.fill = [CPFill fillWithColor:[CPColor blueColor]];
// plotSymbol.lineStyle = symbolLineStyle;
// plotSymbol.size = CGSizeMake(10.0, 10.0);
// dataSourceLinePlot.plotSymbol = plotSymbol;
[graph reloadData];
}
#pragma mark -
#pragma mark Data loading methods
- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
{
// Insert code here to write your document to data of the specified type. If the given outError != NULL, ensure that you set *outError when returning nil.
// You can also choose to override -fileWrapperOfType:error:, -writeToURL:ofType:error:, or -writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead.
// For applications targeted for Panther or earlier systems, you should use the deprecated API -dataRepresentationOfType:. In this case you can also choose to override -fileWrapperRepresentationOfType: or -writeToFile:ofType: instead.
if ( outError != NULL ) {
*outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:NULL];
}
return nil;
}
- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError
{
if ([typeName isEqualToString:@"CSVDocument"]) {
minimumValueForXAxis = MAXFLOAT;
maximumValueForXAxis = -MAXFLOAT;
minimumValueForYAxis = MAXFLOAT;
maximumValueForYAxis = -MAXFLOAT;
NSString *fileContents = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
// Parse CSV
NSUInteger length = [fileContents length];
NSUInteger lineStart = 0, lineEnd = 0, contentsEnd = 0;
NSRange currentRange;
// Read headers from the first line of the file
[fileContents getParagraphStart:&lineStart end:&lineEnd contentsEnd:&contentsEnd forRange:NSMakeRange(lineEnd, 0)];
currentRange = NSMakeRange(lineStart, contentsEnd - lineStart);
// NSArray *columnHeaders = [[fileContents substringWithRange:currentRange] arrayByParsingCSVLine];
// NSLog([columnHeaders objectAtIndex:0]);
while (lineEnd < length) {
[fileContents getParagraphStart:&lineStart end:&lineEnd contentsEnd:&contentsEnd forRange:NSMakeRange(lineEnd, 0)];
currentRange = NSMakeRange(lineStart, contentsEnd - lineStart);
NSArray *columnValues = [[fileContents substringWithRange:currentRange] arrayByParsingCSVLine];
double xValue = [[columnValues objectAtIndex:0] doubleValue];
double yValue = [[columnValues objectAtIndex:1] doubleValue];
if (xValue < minimumValueForXAxis)
minimumValueForXAxis = xValue;
if (xValue > maximumValueForXAxis)
maximumValueForXAxis = xValue;
if (yValue < minimumValueForYAxis)
minimumValueForYAxis = yValue;
if (yValue > maximumValueForYAxis)
maximumValueForYAxis = yValue;
#ifdef USE_NSDECIMAL
[dataPoints addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:[NSDecimalNumber decimalNumberWithString:[columnValues objectAtIndex:0]], @"x", [NSDecimalNumber decimalNumberWithString:[columnValues objectAtIndex:1]], @"y", nil]];
#else
[dataPoints addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithDouble:xValue], @"x", [NSNumber numberWithDouble:yValue], @"y", nil]];
#endif
// Create a dictionary of the items, keyed to the header titles
// NSDictionary *keyedImportedItems = [[NSDictionary alloc] initWithObjects:columnValues forKeys:columnHeaders];
// Process this
}
majorIntervalLengthForX = (maximumValueForXAxis - minimumValueForXAxis) / 10.0;
majorIntervalLengthForY = (maximumValueForYAxis - minimumValueForYAxis) / 10.0;
[fileContents release];
}
if ( outError != NULL ) {
*outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:NULL];
}
return YES;
}
#pragma mark -
#pragma mark PDF / image export
-(IBAction)exportToPDF:(id)sender;
{
NSSavePanel *pdfSavingDialog = [NSSavePanel savePanel];
[pdfSavingDialog setRequiredFileType:@"pdf"];
if ( [pdfSavingDialog runModalForDirectory:nil file:nil] == NSOKButton )
{
NSData *dataForPDF = [graph dataForPDFRepresentationOfLayer];
[dataForPDF writeToFile:[pdfSavingDialog filename] atomically:NO];
}
}
-(IBAction)exportToPNG:(id)sender;
{
NSSavePanel *pngSavingDialog = [NSSavePanel savePanel];
[pngSavingDialog setRequiredFileType:@"png"];
if ( [pngSavingDialog runModalForDirectory:nil file:nil] == NSOKButton )
{
NSImage *image = [graph imageOfLayer];
NSData *tiffData = [image TIFFRepresentation];
NSBitmapImageRep *tiffRep = [NSBitmapImageRep imageRepWithData:tiffData];
NSData *pngData = [tiffRep representationUsingType:NSPNGFileType properties:nil];
[pngData writeToFile:[pngSavingDialog filename] atomically:NO];
}
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot {
return [dataPoints count];
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
#ifdef USE_NSDECIMAL
NSDecimalNumber *num = [[dataPoints objectAtIndex:index] valueForKey:(fieldEnum == CPScatterPlotFieldX ? @"x" : @"y")];
#else
NSNumber *num = [[dataPoints objectAtIndex:index] valueForKey:(fieldEnum == CPScatterPlotFieldX ? @"x" : @"y")];
#endif
return num;
}
@end
| 08iteng-ipad | examples/DropPlot/CPPlotDocument.m | Objective-C | bsd | 8,153 |
//
// main.m
// StockPlot
//
// Created by Jonathan Saggau on 6/19/09.
// Copyright __MyCompanyName__ 2009. All rights reserved.
//
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
| 08iteng-ipad | examples/StockPlot/main.m | Objective-C | bsd | 366 |
//
// RootViewController.h
// StockPlot
//
// Created by Jonathan Saggau on 6/19/09.
// Copyright __MyCompanyName__ 2009. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "APYahooDataPuller.h"
#import "APYahooDataPullerGraph.h"
NSTimeInterval timeIntervalForNumberOfWeeks(float numberOfWeeks);
@interface RootViewController : UITableViewController <APYahooDataPullerDelegate> {
@private
NSMutableArray *stocks;
APYahooDataPullerGraph *graph;
}
@property(nonatomic, readonly)NSArray *symbols;
- (void)addSymbol:(NSString *)aSymbol;
@end
| 08iteng-ipad | examples/StockPlot/Classes/RootViewController.h | Objective-C | bsd | 580 |
//
// StockPlotAppDelegate.m
// StockPlot
//
// Created by Jonathan Saggau on 6/19/09.
// Copyright __MyCompanyName__ 2009. All rights reserved.
//
#import "StockPlotAppDelegate.h"
#import "RootViewController.h"
@implementation StockPlotAppDelegate
@synthesize window;
@synthesize navigationController;
#pragma mark -
#pragma mark Application lifecycle
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after app launch
[[navigationController navigationBar] setTintColor:[UIColor blackColor]];
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Save data if appropriate
}
#pragma mark -
#pragma mark Memory management
- (void)dealloc {
[navigationController release];
[window release];
[super dealloc];
}
@end
| 08iteng-ipad | examples/StockPlot/Classes/StockPlotAppDelegate.m | Objective-C | bsd | 909 |
//
// RootViewController.m
// StockPlot
//
// Created by Jonathan Saggau on 6/19/09.
// Copyright __MyCompanyName__ 2009. All rights reserved.
//
#import "RootViewController.h"
#import "APYahooDataPuller.h"
@interface RootViewController ()
@property(nonatomic, retain)APYahooDataPullerGraph *graph;
@end
@implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
stocks = [[NSMutableArray alloc] initWithCapacity:4];
[self addSymbol:@"AAPL"];
[self addSymbol:@"GOOG"];
[self addSymbol:@"YHOO"];
[self addSymbol:@"MSFT"];
[self addSymbol:@"^DJI"];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[self navigationItem] setTitle:@"Stocks"];
//the graph will set itself as delegate of the dataPuller when we push it, so we need to reset this.
for (APYahooDataPuller *dp in stocks) {
[dp setDelegate:self];
}
}
- (void)viewDidUnload {
// Release anything that can be recreated in viewDidLoad or on demand.
// e.g. self.myOutlet = nil;
[stocks release]; stocks = nil;
[graph release]; graph = nil;
}
#pragma mark Table view methods
-(void)inspectStock:(APYahooDataPuller *)aStock
{
NSDecimalNumber *high = [aStock overallHigh];
NSDecimalNumber *low = [aStock overallLow];
if ([high isEqualToNumber:[NSDecimalNumber notANumber]] || [low isEqualToNumber:[NSDecimalNumber notANumber]] || [[aStock financialData] count] <= 0) {
NSString *message = [NSString stringWithFormat:@"No information available for %@", [aStock symbol]];
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Alert" message:message delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil];
[av show];
[av release];
}
else {
if(nil == graph)
{
APYahooDataPullerGraph *aGraph = [[APYahooDataPullerGraph alloc] initWithNibName:@"APYahooDataPullerGraph" bundle:nil];
self.graph = aGraph;
[aGraph release];
}
[self.graph setDataPuller:aStock];
[self.navigationController pushViewController:self.graph animated:YES];
}
}
// Override to support row selection in the table view.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
APYahooDataPuller *dp = [stocks objectAtIndex:indexPath.row];
[self inspectStock:dp];
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [stocks count];
}
- (void)setupCell:(UITableViewCell *)cell forStockAtIndex:(NSUInteger )row
{
APYahooDataPuller *dp = [stocks objectAtIndex:row];
[[cell textLabel] setText:[dp symbol]];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateStyle:NSDateFormatterShortStyle];
NSString *startString = @"(NA)";
if([dp startDate])
startString = [df stringFromDate:[dp startDate]];
NSString *endString = @"(NA)";
if ([dp endDate]) {
endString = [df stringFromDate:[dp endDate]];
}
[df release];
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[nf setRoundingMode:NSNumberFormatterRoundHalfUp];
[nf setDecimalSeparator:@"."];
[nf setGroupingSeparator:@","];
[nf setPositiveFormat:@"\u00A4###,##0.00"];
[nf setNegativeFormat:@"(\u00A4###,##0.00)"];
NSString *overallLow = @"(NA)";
if (![[NSDecimalNumber notANumber] isEqual:[dp overallLow]]) {
overallLow = [nf stringFromNumber:[dp overallLow]];
}
NSString *overallHigh = @"(NA)";
if (![[NSDecimalNumber notANumber] isEqual:[dp overallHigh]]) {
overallHigh = [nf stringFromNumber:[dp overallHigh]];
}
[nf release];
[[cell detailTextLabel] setText: [NSString stringWithFormat:@"%@ - %@; Low:%@ High:%@", startString, endString, overallLow, overallHigh]];
UIView *accessory = [cell accessoryView];
if ([dp loadingData]) {
if (![accessory isMemberOfClass:[UIActivityIndicatorView class]]) {
accessory = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[(UIActivityIndicatorView *)accessory setHidesWhenStopped:NO];
[cell setAccessoryView:accessory];
[accessory release];
}
[(UIActivityIndicatorView *) accessory startAnimating];
} else {
if ([accessory isMemberOfClass:[UIActivityIndicatorView class]]) {
[(UIActivityIndicatorView *) accessory stopAnimating];
}
if ([dp staleData]) {
if (![accessory isMemberOfClass:[UIImageView class]]) {
UIImage *caution = [UIImage imageNamed:@"caution.png"];
accessory = [[UIImageView alloc] initWithImage:caution];
[cell setAccessoryView:accessory];
// CGRect frame = accessory.frame;
//#pragma unused (frame)
[accessory release];
}
}
else {
[cell setAccessoryView:nil];
}
}
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"UITableViewCellStyleSubtitle";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
NSUInteger row = indexPath.row;
[self setupCell:cell forStockAtIndex:row];
return cell;
}
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait ||
interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
#pragma mark -
#pragma mark accessors
@synthesize graph;
- (NSMutableArray *)stocks
{
//NSLog(@"in -symbols, returned symbols = %@", symbols);
return stocks;
}
- (NSArray *)symbols
{
//NSLog(@"in -symbols, returned symbols = %@", symbols);
NSMutableArray *symbols = [NSMutableArray arrayWithCapacity:[stocks count]];
for (APYahooDataPuller *dp in stocks) {
[symbols addObject:[dp symbol]];
}
return [NSArray arrayWithArray:symbols];
}
-(void)dataPuller:(APYahooDataPuller *)dp downloadDidFailWithError:(NSError *)error;
{
NSLog(@"dataPuller:%@ downloadDidFailWithError:%@", dp, error);
NSUInteger idx = [stocks indexOfObject:dp];
NSUInteger section = 0;
NSIndexPath *path = [NSIndexPath indexPathForRow:idx inSection:section];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:path];
[self setupCell:cell forStockAtIndex:idx];
}
-(void)dataPullerFinancialDataDidChange:(APYahooDataPuller *)dp;
{
NSLog(@"dataPullerFinancialDataDidChange:%@", dp);
NSUInteger idx = [stocks indexOfObject:dp];
NSUInteger section = 0;
NSIndexPath *path = [NSIndexPath indexPathForRow:idx inSection:section];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:path];
[self setupCell:cell forStockAtIndex:idx];
}
- (void)addSymbol:(NSString *)aSymbol
{
NSTimeInterval secondsAgo = -timeIntervalForNumberOfWeeks(14.0f); //12 weeks ago
NSDate *start = [NSDate dateWithTimeIntervalSinceNow:secondsAgo];
NSDate *end = [NSDate date];
APYahooDataPuller *dp = [[APYahooDataPuller alloc] initWithTargetSymbol:aSymbol targetStartDate:start targetEndDate:end];
[[self stocks] addObject:dp];
[dp fetchIfNeeded];
[dp setDelegate:self];
[dp release];
[[self tableView] reloadData]; //TODO: should reload whole thing
}
- (void)dealloc
{
for (APYahooDataPuller *dp in stocks) {
if (dp.delegate == self) {
dp.delegate = nil;
}
}
[stocks release]; stocks = nil;
[super dealloc];
}
/*
- (void)viewDidLoad {
[super viewDidLoad];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
*/
/*
// Override to support row selection in the table view.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here -- for example, create and push another view controller.
// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
// [self.navigationController pushViewController:anotherViewController animated:YES];
// [anotherViewController release];
}
*/
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source.
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
@end
| 08iteng-ipad | examples/StockPlot/Classes/RootViewController.m | Objective-C | bsd | 11,086 |
#import "NSDictionary+APFinancalData.h"
@interface NSDateFormatter (yahooCSVDateFormatter)
+(NSDateFormatter *)yahooCSVDateFormatter;
@end
@implementation NSDateFormatter (yahooCSVDateFormatter)
+(NSDateFormatter *)yahooCSVDateFormatter
{
static NSDateFormatter *df = nil;
if (!df) {
df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"];
}
return df;
}
@end
@implementation NSDictionary (APFinancalData)
+(id)dictionaryWithCSVLine:(NSString*)csvLine;
{
NSArray *csvChunks = [csvLine componentsSeparatedByString:@","];
NSMutableDictionary *csvDict = [NSMutableDictionary dictionaryWithCapacity:7];
// Date,Open,High,Low,Close,Volume,Adj Close
// 2009-06-08,143.82,144.23,139.43,143.85,33255400,143.85
NSDate *theDate = [[NSDateFormatter yahooCSVDateFormatter] dateFromString:(NSString *)[csvChunks objectAtIndex:0]];
[csvDict setObject:theDate forKey:@"date"];
NSDecimalNumber *theOpen = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:1]];
[csvDict setObject:theOpen forKey:@"open"];
NSDecimalNumber *theHigh = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:2]];
[csvDict setObject:theHigh forKey:@"high"];
NSDecimalNumber *theLow = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:3]];
[csvDict setObject:theLow forKey:@"low"];
NSDecimalNumber *theClose = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:4]];
[csvDict setObject:theClose forKey:@"close"];
NSDecimalNumber *theVolume = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:5]];
[csvDict setObject:theVolume forKey:@"volume"];
NSDecimalNumber *theAdjClose = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:6]];
[csvDict setObject:theAdjClose forKey:@"adjClose"];
//non-mutable autoreleased dict
return [NSDictionary dictionaryWithDictionary:csvDict];
}
@end
| 08iteng-ipad | examples/StockPlot/Classes/NSDictionary+APFinancalData.m | Objective-C | bsd | 2,052 |
//
// APYahooDataPullerGraph.h
// StockPlot
//
// Created by Jonathan Saggau on 6/19/09.
// Copyright 2009 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "APYahooDataPuller.h"
#import "CorePlot-CocoaTouch.h"
@interface APYahooDataPullerGraph : UIViewController <APYahooDataPullerDelegate, CPPlotDataSource> {
CPGraphHostingView *graphHost;
APYahooDataPuller *dataPuller;
@private
CPXYGraph *graph;
}
@property (nonatomic, retain) IBOutlet CPGraphHostingView *graphHost;
@property (nonatomic, retain) APYahooDataPuller *dataPuller;
@end
| 08iteng-ipad | examples/StockPlot/Classes/APYahooDataPullerGraph.h | Objective-C | bsd | 585 |
#import "APYahooDataPuller.h"
#import "NSDictionary+APFinancalData.h"
NSTimeInterval timeIntervalForNumberOfWeeks(float numberOfWeeks)
{
NSTimeInterval seconds = fabs(60.0 * 60.0 * 24.0 * 7.0 * numberOfWeeks);
return seconds;
}
@interface APYahooDataPuller ()
@property (nonatomic, retain) NSMutableData *receivedData;
@property (nonatomic, retain) NSURLConnection *connection;
@property (nonatomic, readwrite, assign) BOOL loadingData;
@property (nonatomic, readwrite, retain) NSDecimalNumber *overallHigh;
@property (nonatomic, readwrite, retain) NSDecimalNumber *overallLow;
@property (nonatomic, readwrite, retain) NSArray *financialData;
-(NSString *)URL;
-(void)notifyFinancesChanged;
-(void)populateWithString:(NSString *)csvString;
@end
@implementation APYahooDataPuller
@synthesize symbol;
@synthesize startDate;
@synthesize endDate;
@synthesize targetStartDate;
@synthesize targetEndDate;
@synthesize targetSymbol;
@synthesize overallLow;
@synthesize overallHigh;
@synthesize receivedData;
@synthesize connection;
@synthesize loadingData;
-(id)delegate
{
return delegate;
}
-(void)setDelegate:(id)aDelegate
{
delegate = aDelegate;
}
- (NSArray *)financialData
{
//NSLog(@"in -financialData, returned financialData = %@", financialData);
return financialData;
}
//convert any NSNumber in financial line to NSDecimalNumber
-(NSDictionary *)sanitizedFinancialLine:(NSDictionary *)theFinancialLine
{
NSMutableDictionary *aFinancialLine = [NSMutableDictionary dictionaryWithDictionary:theFinancialLine];
// NSArray *keys = [NSArray arrayWithObjects:@"adjClose", @"close", @"high", @"low", @"open", @"volume", nil];
for (id key in [aFinancialLine allKeys]) {
id something = [aFinancialLine objectForKey:key];
if ([something respondsToSelector:@selector(decimalValue)]) {
something = [NSDecimalNumber decimalNumberWithDecimal:[(NSNumber *)something decimalValue]];
[aFinancialLine setObject:something forKey:key];
}
}
return [NSDictionary dictionaryWithDictionary:aFinancialLine];
}
- (void)setFinancialData:(NSArray *)aFinancialData
{
//NSLog(@"in -setFinancialData:, old value of financialData: %@, changed to: %@", financialData, aFinancialData);
if (financialData != aFinancialData)
{
NSMutableArray *mutableFinancialData = [aFinancialData mutableCopy];
NSDictionary *financialLine = nil;
NSUInteger i = 0, count = [mutableFinancialData count];
for (i = 0; i < count; i++) {
financialLine = (NSDictionary *) [mutableFinancialData objectAtIndex:i];
financialLine = [self sanitizedFinancialLine:financialLine];
[mutableFinancialData replaceObjectAtIndex:i withObject:financialLine];
}
[financialData release];
financialData = [[NSArray alloc] initWithArray:mutableFinancialData];
[mutableFinancialData release];
if(0 < [financialData count])
[self notifyFinancesChanged];
}
}
- (NSDictionary *)plistRep
{
NSMutableDictionary *rep = [NSMutableDictionary dictionaryWithCapacity:7];
[rep setObject:[self symbol] forKey:@"symbol"];
[rep setObject:[self startDate] forKey:@"startDate"];
[rep setObject:[self endDate] forKey:@"endDate"];
[rep setObject:[self overallHigh] forKey:@"overallHigh"];
[rep setObject:[self overallLow] forKey:@"overallLow"];
[rep setObject:[self financialData] forKey:@"financalData"];
return [NSDictionary dictionaryWithDictionary:rep];
}
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag;
{
NSLog(@"writeToFile:%@", path);
BOOL success = [[self plistRep] writeToFile:path atomically:flag];
return success;
}
-(id)initWithDictionary:(NSDictionary *)aDict targetSymbol:(NSString *)aSymbol targetStartDate:(NSDate *)aStartDate targetEndDate:(NSDate *)anEndDate
{
self = [super init];
if (self != nil) {
self.symbol = [aDict objectForKey:@"symbol"];
self.startDate = [aDict objectForKey:@"startDate"];
self.overallLow = [NSDecimalNumber decimalNumberWithDecimal:[[aDict objectForKey:@"overallLow"] decimalValue]];
self.overallHigh = [NSDecimalNumber decimalNumberWithDecimal:[[aDict objectForKey:@"overallHigh"] decimalValue]];
self.endDate = [aDict objectForKey:@"endDate"];
self.financialData = [aDict objectForKey:@"financalData"];
self.targetSymbol = aSymbol;
self.targetStartDate = aStartDate;
self.targetEndDate = anEndDate;
}
return self;
}
-(NSString *)pathForSymbol:(NSString *)aSymbol
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *docPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", aSymbol]];
return docPath;
}
-(NSString *)faultTolerantPathForSymbol:(NSString *)aSymbol
{
NSString *docPath = [self pathForSymbol:aSymbol];;
if (![[NSFileManager defaultManager] fileExistsAtPath:docPath]) {
//if there isn't one in the user's documents directory, see if we ship with this data
docPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", aSymbol]];
}
return docPath;
}
//Always returns *something*
-(NSDictionary *)dictionaryForSymbol:(NSString *)aSymbol
{
NSString *path = [self faultTolerantPathForSymbol:aSymbol];
NSMutableDictionary *localPlistDict = [NSMutableDictionary dictionaryWithContentsOfFile:path];
return localPlistDict;
}
-(id)initWithTargetSymbol:(NSString *)aSymbol targetStartDate:(NSDate *)aStartDate targetEndDate:(NSDate *)anEndDate
{
NSDictionary *cachedDictionary = [self dictionaryForSymbol:aSymbol];
if (nil != cachedDictionary)
{
return [self initWithDictionary:cachedDictionary targetSymbol:aSymbol targetStartDate:aStartDate targetEndDate:anEndDate];
}
NSMutableDictionary *rep = [NSMutableDictionary dictionaryWithCapacity:7];
[rep setObject:aSymbol forKey:@"symbol"];
[rep setObject:aStartDate forKey:@"startDate"];
[rep setObject:anEndDate forKey:@"endDate"];
[rep setObject:[NSDecimalNumber notANumber] forKey:@"overallHigh"];
[rep setObject:[NSDecimalNumber notANumber] forKey:@"overallLow"];
[rep setObject:[NSArray array] forKey:@"financalData"];
return [self initWithDictionary:rep targetSymbol:aSymbol targetStartDate:aStartDate targetEndDate:anEndDate];
}
-(id)init
{
NSTimeInterval secondsAgo = -timeIntervalForNumberOfWeeks(14.0f); //12 weeks ago
NSDate *start = [NSDate dateWithTimeIntervalSinceNow:secondsAgo];
NSDate *end = [NSDate date];
return [self initWithTargetSymbol:@"AAPL" targetStartDate:start targetEndDate:end];
}
-(void)dealloc
{
[symbol release];
[startDate release];
[endDate release];
[financialData release];
symbol = nil;
startDate = nil;
endDate = nil;
financialData = nil;
delegate = nil;
[super dealloc];
}
// http://www.goldb.org/ystockquote.html
-(NSString *)URL;
{
unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *compsStart = [gregorian components:unitFlags fromDate:targetStartDate];
NSDateComponents *compsEnd = [gregorian components:unitFlags fromDate:targetEndDate];
[gregorian release];
NSString *url = [NSString stringWithFormat:@"http://ichart.yahoo.com/table.csv?s=%@&", [self targetSymbol]];
url = [url stringByAppendingFormat:@"a=%d&", [compsStart month]-1];
url = [url stringByAppendingFormat:@"b=%d&", [compsStart day]];
url = [url stringByAppendingFormat:@"c=%d&", [compsStart year]];
url = [url stringByAppendingFormat:@"d=%d&", [compsEnd month]-1];
url = [url stringByAppendingFormat:@"e=%d&", [compsEnd day]];
url = [url stringByAppendingFormat:@"f=%d&", [compsEnd year]];
url = [url stringByAppendingString:@"g=d&"];
url = [url stringByAppendingString:@"ignore=.csv"];
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return url;
}
-(void)notifyFinancesChanged
{
if (delegate && [delegate respondsToSelector:@selector(dataPullerFinancialDataDidChange:)]) {
[delegate performSelector:@selector(dataPullerFinancialDataDidChange:) withObject:self];
}
}
#pragma mark -
#pragma mark Downloading of data
-(BOOL)staleData
{
NSTimeInterval twelveHours = 60.0f * 60.f * 12.0f;
return (0 >= self.financialData.count ||
![[self targetSymbol] isEqualToString:[self symbol]] ||
[[self targetStartDate] timeIntervalSinceDate:[self startDate]] > twelveHours ||
[[self targetEndDate] timeIntervalSinceDate:[self endDate]] > twelveHours);
}
-(void)fetchIfNeeded
{
if ( self.loadingData ) return;
//Check to see if cached data is stale
if ([self staleData])
{
self.loadingData = YES;
NSString *urlString = [self URL];
NSLog(@"Fetching URL %@", urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
self.connection = [NSURLConnection connectionWithRequest:theRequest delegate:self];
if (self.connection) {
self.receivedData = [NSMutableData data];
}
else {
self.loadingData = NO;
}
}
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// append the new data to the receivedData
[self.receivedData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// this method is called when the server has determined that it
// has enough information to create the NSURLResponse
// it can be called multiple times, for example in the case of a
// redirect, so each time we reset the data.
[self.receivedData setLength:0];
}
-(void)cancelDownload
{
if (self.loadingData) {
[self.connection cancel];
self.loadingData = NO;
self.receivedData = nil;
self.connection = nil;
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
self.loadingData = NO;
self.receivedData = nil;
self.connection = nil;
NSLog(@"err = %@", [error localizedDescription]);
self.connection = nil;
if(delegate && [delegate respondsToSelector:@selector(dataPuller:downloadDidFailWithError:)])
{
[delegate performSelector:@selector(dataPuller:downloadDidFailWithError:) withObject:self withObject:error];
}
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.loadingData = NO;
self.connection = nil;
NSString *csv = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];
[self populateWithString:csv];
self.receivedData = nil;
[self writeToFile:[self pathForSymbol:self.symbol] atomically:YES];
}
-(void)populateWithString:(NSString *)csvString;
{
NSArray *csvLines = [csvString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSMutableArray *newFinancials = [NSMutableArray arrayWithCapacity:[csvLines count]];
NSDictionary *currentFinancial = nil;
NSString *line = nil;
self.overallHigh = [NSDecimalNumber notANumber];
self.overallLow = [NSDecimalNumber notANumber];
for (NSUInteger i=1; i<[csvLines count]-1; i++) {
line = (NSString *)[csvLines objectAtIndex:i];
currentFinancial = [NSDictionary dictionaryWithCSVLine:line];
[newFinancials addObject:currentFinancial];
NSDecimalNumber *high = [currentFinancial objectForKey:@"high"];
NSDecimalNumber *low = [currentFinancial objectForKey:@"low"];
if ( [self.overallHigh isEqual:[NSDecimalNumber notANumber]] ) {
self.overallHigh = high;
}
if ( [self.overallLow isEqual:[NSDecimalNumber notANumber]] ) {
self.overallLow = low;
}
if ( [low compare:self.overallLow] == NSOrderedAscending ) {
self.overallLow = low;
}
if ( [high compare:self.overallHigh] == NSOrderedDescending ) {
self.overallHigh = high;
}
}
self.startDate = self.targetStartDate;
self.endDate = self.targetEndDate;
self.symbol = self.targetSymbol;
[self setFinancialData:[NSArray arrayWithArray:newFinancials]];
}
@end
| 08iteng-ipad | examples/StockPlot/Classes/APYahooDataPuller.m | Objective-C | bsd | 13,072 |
#import <Foundation/Foundation.h>
@class APYahooDataPuller;
@protocol APYahooDataPullerDelegate
@optional
-(void)dataPullerFinancialDataDidChange:(APYahooDataPuller *)dp;
-(void)dataPuller:(APYahooDataPuller *)dp downloadDidFailWithError:(NSError *)error;
@end
@interface APYahooDataPuller : NSObject {
NSString *symbol;
NSDate *startDate;
NSDate *endDate;
NSDate *targetStartDate;
NSDate *targetEndDate;
NSString *targetSymbol;
id delegate;
NSDecimalNumber *overallHigh;
NSDecimalNumber *overallLow;
BOOL loadingData;
BOOL staleData;
@private
NSArray *financialData; // consists of dictionaries
NSMutableData *receivedData;
NSURLConnection *connection;
}
@property (nonatomic, assign) id delegate;
@property (nonatomic, copy) NSString *symbol;
@property (nonatomic, retain) NSDate *startDate;
@property (nonatomic, retain) NSDate *endDate;
@property (nonatomic, copy) NSString *targetSymbol;
@property (nonatomic, retain) NSDate *targetStartDate;
@property (nonatomic, retain) NSDate *targetEndDate;
@property (nonatomic, readonly, retain) NSArray *financialData;
@property (nonatomic, readonly, retain) NSDecimalNumber *overallHigh;
@property (nonatomic, readonly, retain) NSDecimalNumber *overallLow;
@property (nonatomic, readonly, assign) BOOL loadingData;
@property (nonatomic, readonly, assign) BOOL staleData;
-(id)initWithTargetSymbol:(NSString *)aSymbol targetStartDate:(NSDate *)aStartDate targetEndDate:(NSDate *)anEndDate;
-(void)fetchIfNeeded;
-(void)cancelDownload;
@end
| 08iteng-ipad | examples/StockPlot/Classes/APYahooDataPuller.h | Objective-C | bsd | 1,572 |
//
// StockPlotAppDelegate.h
// StockPlot
//
// Created by Jonathan Saggau on 6/19/09.
// Copyright __MyCompanyName__ 2009. All rights reserved.
//
@interface StockPlotAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
UINavigationController *navigationController;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
@end
| 08iteng-ipad | examples/StockPlot/Classes/StockPlotAppDelegate.h | Objective-C | bsd | 451 |
#import <Foundation/Foundation.h>
@interface NSDictionary (APFinancalData)
+(id)dictionaryWithCSVLine:(NSString*)csvLine;
@end
| 08iteng-ipad | examples/StockPlot/Classes/NSDictionary+APFinancalData.h | Objective-C | bsd | 130 |
//
// APYahooDataPullerGraph.m
// StockPlot
//
// Created by Jonathan Saggau on 6/19/09.
// Copyright 2009 __MyCompanyName__. All rights reserved.
//
#import "APYahooDataPullerGraph.h"
@implementation APYahooDataPullerGraph
-(void)reloadData
{
if(!graph)
{
graph = [[CPXYGraph alloc] initWithFrame:CGRectZero];
CPTheme *theme = [CPTheme themeNamed:@"Dark Gradients"];
[graph applyTheme:theme];
graph.paddingTop = 30.0;
graph.paddingBottom = 30.0;
graph.paddingLeft = 50.0;
graph.paddingRight = 50.0;
CPScatterPlot *dataSourceLinePlot = [[[CPScatterPlot alloc] initWithFrame:graph.bounds] autorelease];
dataSourceLinePlot.identifier = @"Data Source Plot";
CPMutableLineStyle *lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.lineWidth = 1.f;
lineStyle.lineColor = [CPColor redColor];
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.dataSource = self;
[graph addPlot:dataSourceLinePlot];
}
if([[self.graphHost.layer sublayers] indexOfObject:graph] == NSNotFound)
[self.graphHost.layer addSublayer:graph];
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
NSDecimalNumber *high = [dataPuller overallHigh];
NSDecimalNumber *low = [dataPuller overallLow];
NSDecimalNumber *length = [high decimalNumberBySubtracting:low];
//NSLog(@"high = %@, low = %@, length = %@", high, low, length);
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromUnsignedInteger([dataPuller.financialData count])];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:[low decimalValue] length:[length decimalValue]];
// Axes
CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.majorIntervalLength = CPDecimalFromDouble(10.0);
x.orthogonalCoordinateDecimal = CPDecimalFromInteger(0);
x.minorTicksPerInterval = 1;
CPXYAxis *y = axisSet.yAxis;
NSDecimal six = CPDecimalFromInteger(6);
y.majorIntervalLength = CPDecimalDivide([length decimalValue], six);
y.majorTickLineStyle = nil;
y.minorTicksPerInterval = 4;
y.minorTickLineStyle = nil;
y.orthogonalCoordinateDecimal = CPDecimalFromInteger(0);
y.alternatingBandFills = [NSArray arrayWithObjects:[[CPColor whiteColor] colorWithAlphaComponent:0.1], [NSNull null], nil];
[graph reloadData];
[[self navigationItem] setTitle:[dataPuller symbol]];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
graph.frame = self.view.bounds;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
[self reloadData];
}
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait ||
interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration;
{
// NSLog(@"willRotateToInterfaceOrientation");
//[graph.axisSet relabelAxes];
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation;
{
// NSLog(@"didRotateFromInterfaceOrientation");
[graph.axisSet relabelAxes];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecords {
return self.dataPuller.financialData.count;
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
NSDecimalNumber *num = [NSDecimalNumber zero];
if (fieldEnum == CPScatterPlotFieldX)
{
num = (NSDecimalNumber *) [NSDecimalNumber numberWithInt:index + 1];
}
else if (fieldEnum == CPScatterPlotFieldY)
{
NSArray *financialData = self.dataPuller.financialData;
NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:[financialData count] - index - 1];
num = [fData objectForKey:@"close"];
NSAssert([num isMemberOfClass:[NSDecimalNumber class]], @"grrr");
}
return num;
}
-(void)dataPullerFinancialDataDidChange:(APYahooDataPuller *)dp;
{
[self reloadData];
}
#pragma mark accessors
@synthesize graphHost;
- (APYahooDataPuller *)dataPuller
{
//NSLog(@"in -dataPuller, returned dataPuller = %@", dataPuller);
return dataPuller;
}
- (void)setDataPuller:(APYahooDataPuller *)aDataPuller
{
//NSLog(@"in -setDataPuller:, old value of dataPuller: %@, changed to: %@", dataPuller, aDataPuller);
if (dataPuller != aDataPuller) {
[aDataPuller retain];
[dataPuller release];
dataPuller = aDataPuller;
[dataPuller setDelegate:self];
[self reloadData];
}
}
- (void)dealloc {
if(dataPuller.delegate == self)
[dataPuller setDelegate:nil];
[dataPuller release]; dataPuller = nil;
[graphHost release]; graphHost = nil;
[graph release]; graph = nil;
[super dealloc];
}
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot {
return [self numberOfRecords];
}
@end
| 08iteng-ipad | examples/StockPlot/Classes/APYahooDataPullerGraph.m | Objective-C | bsd | 5,823 |
//
// main.m
// CPTestApp-iPhone
//
// Created by Brad Larson on 5/11/2009.
//
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
| 08iteng-ipad | examples/CPTestApp-iPhone-SpeedTest/main.m | Objective-C | bsd | 308 |
//
// TestXYTheme.m
// CPTestApp-iPhone
//
// Created by Joan on 03/06/10.
// Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import "TestXYTheme.h"
@implementation TestXYTheme
+(NSString *)defaultName
{
return kCPDarkGradientTheme;
}
-(void)applyThemeToAxis:(CPXYAxis *)axis usingMajorLineStyle:(CPLineStyle *)majorLineStyle
minorLineStyle:(CPLineStyle *)minorLineStyle majorGridLineStyle:majorGridLineStyle textStyle:(CPTextStyle *)textStyle
{
axis.labelingPolicy = CPAxisLabelingPolicyFixedInterval;
axis.majorIntervalLength = CPDecimalFromDouble(20.0);
axis.orthogonalCoordinateDecimal = CPDecimalFromDouble(0.0);
axis.tickDirection = CPSignNone;
axis.minorTicksPerInterval = 3;
axis.majorTickLineStyle = majorLineStyle;
axis.minorTickLineStyle = minorLineStyle;
axis.axisLineStyle = majorLineStyle;
axis.majorTickLength = 5.0f;
axis.minorTickLength = 3.0f;
axis.labelTextStyle = textStyle;
axis.titleTextStyle = textStyle;
//axis.labelFormatter = numberFormatter ;
axis.majorGridLineStyle = majorGridLineStyle ;
axis.labelingPolicy = CPAxisLabelingPolicyAutomatic ;
}
-(void)applyThemeToBackground:(CPXYGraph *)graph
{
CPColor *endColor = [CPColor colorWithGenericGray:0.1f];
CPGradient *graphGradient = [CPGradient gradientWithBeginningColor:endColor endingColor:endColor];
graphGradient = [graphGradient addColorStop:[CPColor colorWithGenericGray:0.2f] atPosition:0.3f];
graphGradient = [graphGradient addColorStop:[CPColor colorWithGenericGray:0.3f] atPosition:0.5f];
graphGradient = [graphGradient addColorStop:[CPColor colorWithGenericGray:0.2f] atPosition:0.6f];
graphGradient.angle = 90.0f;
graph.fill = [CPFill fillWithGradient:graphGradient];
}
-(void)applyThemeToPlotArea:(CPPlotAreaFrame *)plotAreaFrame
{
CPGradient *gradient = [CPGradient gradientWithBeginningColor:[CPColor colorWithGenericGray:0.1f] endingColor:[CPColor colorWithGenericGray:0.3f]];
gradient.angle = 90.0f;
plotAreaFrame.fill = [CPFill fillWithGradient:gradient];
plotAreaFrame.paddingLeft = 50 ;
plotAreaFrame.paddingTop = 10 ;
plotAreaFrame.paddingRight = 20 ;
plotAreaFrame.paddingBottom = 30 ;
}
-(void)applyThemeToAxisSet:(CPXYAxisSet *)axisSet {
CPMutableLineStyle *majorLineStyle = [CPMutableLineStyle lineStyle];
majorLineStyle.lineCap = kCGLineCapSquare;
majorLineStyle.lineColor = [CPColor grayColor];
majorLineStyle.lineWidth = 2.0f;
CPMutableLineStyle *minorLineStyle = [CPMutableLineStyle lineStyle];
minorLineStyle.lineCap = kCGLineCapSquare;
minorLineStyle.lineColor = [CPColor grayColor];
minorLineStyle.lineWidth = 1.0f;
CPMutableLineStyle *majorGridLineStyle = [CPMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.1f;
majorGridLineStyle.lineColor = [CPColor lightGrayColor];
CPMutableLineStyle *minorGridLineStyle = [CPMutableLineStyle lineStyle];
minorGridLineStyle.lineWidth = 0.25f;
minorGridLineStyle.lineColor = [CPColor blueColor];
CPMutableTextStyle *whiteTextStyle = [[[CPMutableTextStyle alloc] init] autorelease];
whiteTextStyle.color = [CPColor whiteColor];
whiteTextStyle.fontSize = 14.0f;
[self applyThemeToAxis:axisSet.xAxis usingMajorLineStyle:majorLineStyle minorLineStyle:minorLineStyle majorGridLineStyle:majorGridLineStyle textStyle:whiteTextStyle];
[self applyThemeToAxis:axisSet.yAxis usingMajorLineStyle:majorLineStyle minorLineStyle:minorLineStyle majorGridLineStyle:majorGridLineStyle textStyle:whiteTextStyle];
}
@end
| 08iteng-ipad | examples/CPTestApp-iPhone-SpeedTest/Classes/TestXYTheme.m | Objective-C | bsd | 3,569 |
#import <UIKit/UIKit.h>
#import "CorePlot-CocoaTouch.h"
@interface CPTestAppPieChartController : UIViewController <CPPieChartDataSource>
{
@private
CPXYGraph *pieChart;
NSMutableArray *dataForChart;
}
@property(readwrite, retain, nonatomic) NSMutableArray *dataForChart;
@end
| 08iteng-ipad | examples/CPTestApp-iPhone-SpeedTest/Classes/CPTestAppPieChartController.h | Objective-C | bsd | 283 |
//
// CPTestAppBarChartController.h
// CPTestApp-iPhone
//
#import <UIKit/UIKit.h>
#import "CorePlot-CocoaTouch.h"
@interface CPTestAppBarChartController : UIViewController <CPPlotDataSource>
{
CPXYGraph *barChart;
}
@end
| 08iteng-ipad | examples/CPTestApp-iPhone-SpeedTest/Classes/CPTestAppBarChartController.h | Objective-C | bsd | 229 |
//
// TestXYTheme.h
// CPTestApp-iPhone
//
// Created by Joan on 03/06/10.
// Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "CorePlot-CocoaTouch.h"
@interface TestXYTheme : CPXYTheme
{
}
@end
| 08iteng-ipad | examples/CPTestApp-iPhone-SpeedTest/Classes/TestXYTheme.h | Objective-C | bsd | 258 |
//
// CPTestApp_iPhoneAppDelegate.m
// CPTestApp-iPhone
//
// Created by Brad Larson on 5/11/2009.
#import "CPTestApp_iPhoneAppDelegate.h"
@implementation CPTestApp_iPhoneAppDelegate
@synthesize window;
@synthesize tabBarController;
-(void)applicationDidFinishLaunching:(UIApplication *)application {
// Add the tab bar controller's current view as a subview of the window
[window addSubview:tabBarController.view];
}
/*
// Optional UITabBarControllerDelegate method
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
}
*/
/*
// Optional UITabBarControllerDelegate method
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed {
}
*/
-(void)dealloc {
[tabBarController release];
[window release];
[super dealloc];
}
@end
| 08iteng-ipad | examples/CPTestApp-iPhone-SpeedTest/Classes/CPTestApp_iPhoneAppDelegate.m | Objective-C | bsd | 926 |
#import "CPTestAppPieChartController.h"
@implementation CPTestAppPieChartController
@synthesize dataForChart;
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
return YES;
}
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
CPPlot *piePlot = [pieChart plotWithIdentifier:@"Pie Chart 1"];
CGRect plotBounds = pieChart.plotAreaFrame.bounds;
((CPPieChart *)piePlot).pieRadius = MIN(plotBounds.size.width, plotBounds.size.height) / 2.0 - 10.0;
}
#pragma mark -
#pragma mark Initialization and teardown
-(void)dealloc
{
[dataForChart release];
[super dealloc];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Create pieChart from theme
pieChart = [[CPXYGraph alloc] initWithFrame:CGRectZero];
CPTheme *theme = [CPTheme themeNamed:kCPDarkGradientTheme];
[pieChart applyTheme:theme];
CPGraphHostingView *hostingView = (CPGraphHostingView *)self.view;
hostingView.hostedGraph = pieChart;
pieChart.paddingLeft = 20.0;
pieChart.paddingTop = 20.0;
pieChart.paddingRight = 20.0;
pieChart.paddingBottom = 20.0;
pieChart.axisSet = nil;
// Add pie chart
CPPieChart *piePlot = [[CPPieChart alloc] init];
piePlot.dataSource = self;
piePlot.pieRadius = 130.0;
piePlot.identifier = @"Pie Chart 1";
piePlot.startAngle = M_PI_4;
piePlot.sliceDirection = CPPieDirectionCounterClockwise;
[pieChart addPlot:piePlot];
[piePlot release];
// Add some initial data
NSMutableArray *contentArray = [NSMutableArray arrayWithObjects:[NSNumber numberWithDouble:20.0], [NSNumber numberWithDouble:30.0], [NSNumber numberWithDouble:60.0], nil];
self.dataForChart = contentArray;
#ifdef PERFORMANCE_TEST
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(changePlotRange) userInfo:nil repeats:YES];
#endif
}
-(void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
return [self.dataForChart count];
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
if ( index >= [self.dataForChart count] ) return nil;
if ( fieldEnum == CPPieChartFieldSliceWidth ) {
return [self.dataForChart objectAtIndex:index];
}
else {
return [NSNumber numberWithInt:index];
}
}
/*-(CPFill *)sliceFillForPieChart:(CPPieChart *)pieChart recordIndex:(NSUInteger)index;
{
return nil;
}*/
@end
| 08iteng-ipad | examples/CPTestApp-iPhone-SpeedTest/Classes/CPTestAppPieChartController.m | Objective-C | bsd | 2,651 |
//
// CPTestApp_iPhoneAppDelegate.h
// CPTestApp-iPhone
//
// Toolbar icons in the application are courtesy of Joseph Wain / glyphish.com
// See the license file in the GlyphishIcons directory for more information on these icons
#import <UIKit/UIKit.h>
@interface CPTestApp_iPhoneAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate> {
UIWindow *window;
UITabBarController *tabBarController;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UITabBarController *tabBarController;
@end
| 08iteng-ipad | examples/CPTestApp-iPhone-SpeedTest/Classes/CPTestApp_iPhoneAppDelegate.h | Objective-C | bsd | 570 |
//
// CPTestAppScatterPlotController.m
// CPTestApp-iPhone
//
// Created by Brad Larson on 5/11/2009.
//
#import "CPTestAppScatterPlotController.h"
#import "TestXYTheme.h"
#define USE_DOUBLEFASTPATH true
#define USE_ONEVALUEPATH false
@implementation CPTestAppScatterPlotController
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
return YES;
}
#pragma mark -
#pragma mark Initialization and teardown
-(void)dealloc
{
[graph release] ;
[super dealloc];
}
-(void)viewDidLoad
{
[super viewDidLoad];
// Create graph from a custom theme
graph = [[CPXYGraph alloc] initWithFrame:CGRectZero];
CPTheme *theme = [[TestXYTheme alloc] init] ;
[graph applyTheme:theme];
[theme release] ;
CPGraphHostingView *hostingView = (CPGraphHostingView *)self.view;
hostingView.hostedGraph = graph;
// Setup plot space
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = NO;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0) length:CPDecimalFromFloat(NUM_POINTS)];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0) length:CPDecimalFromFloat(NUM_POINTS)];
// Create a blue plot area
CPScatterPlot *boundLinePlot = [[[CPScatterPlot alloc] init] autorelease];
boundLinePlot.identifier = @"Blue Plot";
CPMutableLineStyle *lineStyle = [[boundLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.lineWidth = 1.0f;
lineStyle.lineColor = [CPColor blueColor];
boundLinePlot.dataLineStyle = lineStyle;
boundLinePlot.dataSource = self;
[graph addPlot:boundLinePlot];
// Create a green plot area
CPScatterPlot *dataSourceLinePlot = [[[CPScatterPlot alloc] init] autorelease];
dataSourceLinePlot.identifier = @"Green Plot";
lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.lineWidth = 1.0f;
lineStyle.lineColor = [CPColor greenColor];
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.dataSource = self;
[graph addPlot:dataSourceLinePlot] ;
NSUInteger i;
for ( i = 0; i < NUM_POINTS; i++ ) {
xxx[i] = i ;
yyy1[i] = (NUM_POINTS/3)*(rand()/(float)RAND_MAX);
yyy2[i] = (NUM_POINTS/3)*(rand()/(float)RAND_MAX) + NUM_POINTS/3;
}
#define PERFORMANCE_TEST1
#ifdef PERFORMANCE_TEST1
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(changePlotRange) userInfo:nil repeats:YES];
#endif
#ifdef PERFORMANCE_TEST2
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(reloadPlots) userInfo:nil repeats:YES];
#endif
}
- (void)reloadPlots
{
NSArray *plots = [graph allPlots] ;
for ( CPPlot *plot in plots )
{
[plot reloadData] ;
}
}
-(void)changePlotRange
{
// Setup plot space
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
float ylen = NUM_POINTS*(rand()/(float)RAND_MAX) ;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0) length:CPDecimalFromFloat(NUM_POINTS)];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0) length:CPDecimalFromFloat(ylen)];
}
#pragma mark -
#pragma mark Plot Data
- (double *)valuesForPlotWithIdentifier:(id)identifier field:(NSUInteger)fieldEnum
{
if ( fieldEnum == 0 ) return xxx ;
else
{
if ( [identifier isEqualToString:@"Blue Plot"] ) return yyy1 ;
else return yyy2 ;
}
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
return NUM_POINTS ;
}
#if USE_DOUBLEFASTPATH
#if USE_ONEVALUEPATH
- (double)doubleForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)indx
{
double *values = [self valuesForPlotWithIdentifier:[plot identifier] field:fieldEnum] ;
return values[indx] ;
}
#else
- (double *)doublesForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndexRange:(NSRange)indexRange
{
double *values = [self valuesForPlotWithIdentifier:[plot identifier] field:fieldEnum] ;
return values + indexRange.location ;
}
#endif
#else
#if USE_ONEVALUEPATH
- (NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)indx
{
NSNumber *num = nil ;
double *values = [self valuesForPlotWithIdentifier:[plot identifier] field:fieldEnum] ;
if ( values ) num = [NSNumber numberWithDouble:values[indx]] ;
return num ;
}
#else
- (NSArray *)numbersForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndexRange:(NSRange)indexRange
{
double *values = [self valuesForPlotWithIdentifier:[plot identifier] field:fieldEnum] ;
if ( values == NULL ) return nil ;
NSMutableArray *returnArray = [NSMutableArray arrayWithCapacity:indexRange.length] ;
for ( NSUInteger i=indexRange.location ; i<indexRange.location+indexRange.length ; i++ )
{
NSNumber *number = [[NSNumber alloc] initWithDouble:values[i]] ;
[returnArray addObject:number] ;
[number release] ;
}
return returnArray ;
}
#endif
#endif
@end
| 08iteng-ipad | examples/CPTestApp-iPhone-SpeedTest/Classes/CPTestAppScatterPlotController.m | Objective-C | bsd | 5,195 |
//
// CPTestAppScatterPlotController.h
// CPTestApp-iPhone
//
// Created by Brad Larson on 5/11/2009.
//
#import <UIKit/UIKit.h>
#import "CorePlot-CocoaTouch.h"
#define NUM_POINTS 500
@interface CPTestAppScatterPlotController : UIViewController <CPPlotDataSource>
{
CPXYGraph *graph;
double xxx[NUM_POINTS] ;
double yyy1[NUM_POINTS] ;
double yyy2[NUM_POINTS] ;
}
@end
| 08iteng-ipad | examples/CPTestApp-iPhone-SpeedTest/Classes/CPTestAppScatterPlotController.h | Objective-C | bsd | 388 |
//
// CPTestAppBarChartController.m
// CPTestApp-iPhone
//
#import "CPTestAppBarChartController.h"
@implementation CPTestAppBarChartController
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
return YES;
}
#pragma mark -
#pragma mark Initialization and teardown
- (void)viewDidLoad
{
[super viewDidLoad];
// Create barChart from theme
barChart = [[CPXYGraph alloc] initWithFrame:CGRectZero];
CPTheme *theme = [CPTheme themeNamed:kCPDarkGradientTheme];
[barChart applyTheme:theme];
CPGraphHostingView *hostingView = (CPGraphHostingView *)self.view;
hostingView.hostedGraph = barChart;
barChart.plotAreaFrame.masksToBorder = NO;
barChart.paddingLeft = 70.0;
barChart.paddingTop = 20.0;
barChart.paddingRight = 20.0;
barChart.paddingBottom = 80.0;
// Add plot space for horizontal bar charts
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)barChart.defaultPlotSpace;
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0f) length:CPDecimalFromFloat(300.0f)];
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0f) length:CPDecimalFromFloat(16.0f)];
CPXYAxisSet *axisSet = (CPXYAxisSet *)barChart.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.axisLineStyle = nil;
x.majorTickLineStyle = nil;
x.minorTickLineStyle = nil;
x.majorIntervalLength = CPDecimalFromString(@"5");
x.orthogonalCoordinateDecimal = CPDecimalFromString(@"0");
x.title = @"X Axis";
x.titleLocation = CPDecimalFromFloat(7.5f);
x.titleOffset = 55.0f;
// Define some custom labels for the data elements
x.labelRotation = M_PI/4;
x.labelingPolicy = CPAxisLabelingPolicyNone;
NSArray *customTickLocations = [NSArray arrayWithObjects:[NSDecimalNumber numberWithInt:1], [NSDecimalNumber numberWithInt:5], [NSDecimalNumber numberWithInt:10], [NSDecimalNumber numberWithInt:15], nil];
NSArray *xAxisLabels = [NSArray arrayWithObjects:@"Label A", @"Label B", @"Label C", @"Label D", @"Label E", nil];
NSUInteger labelLocation = 0;
NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:[xAxisLabels count]];
for (NSNumber *tickLocation in customTickLocations) {
CPAxisLabel *newLabel = [[CPAxisLabel alloc] initWithText: [xAxisLabels objectAtIndex:labelLocation++] textStyle:x.labelTextStyle];
newLabel.tickLocation = [tickLocation decimalValue];
newLabel.offset = x.labelOffset + x.majorTickLength;
newLabel.rotation = M_PI/4;
[customLabels addObject:newLabel];
[newLabel release];
}
x.axisLabels = [NSSet setWithArray:customLabels];
CPXYAxis *y = axisSet.yAxis;
y.axisLineStyle = nil;
y.majorTickLineStyle = nil;
y.minorTickLineStyle = nil;
y.majorIntervalLength = CPDecimalFromString(@"50");
y.orthogonalCoordinateDecimal = CPDecimalFromString(@"0");
y.title = @"Y Axis";
y.titleOffset = 45.0f;
y.titleLocation = CPDecimalFromFloat(150.0f);
// First bar plot
CPBarPlot *barPlot = [CPBarPlot tubularBarPlotWithColor:[CPColor darkGrayColor] horizontalBars:NO];
barPlot.baseValue = CPDecimalFromString(@"0");
barPlot.dataSource = self;
barPlot.barOffset = CPDecimalFromFloat(-0.25f);
barPlot.identifier = @"Bar Plot 1";
[barChart addPlot:barPlot toPlotSpace:plotSpace];
// Second bar plot
barPlot = [CPBarPlot tubularBarPlotWithColor:[CPColor blueColor] horizontalBars:NO];
barPlot.dataSource = self;
barPlot.baseValue = CPDecimalFromString(@"0");
barPlot.barOffset = CPDecimalFromFloat(0.25f);
barPlot.barCornerRadius = 2.0f;
barPlot.identifier = @"Bar Plot 2";
[barChart addPlot:barPlot toPlotSpace:plotSpace];
#ifdef PERFORMANCE_TEST
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(changePlotRange) userInfo:nil repeats:YES];
#endif
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot {
return 16;
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSDecimalNumber *num = nil;
if ( [plot isKindOfClass:[CPBarPlot class]] ) {
switch ( fieldEnum ) {
case CPBarPlotFieldBarLocation:
num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:index];
break;
case CPBarPlotFieldBarTip:
num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:(index+1)*(index+1)];
if ( [plot.identifier isEqual:@"Bar Plot 2"] )
num = [num decimalNumberBySubtracting:[NSDecimalNumber decimalNumberWithString:@"10"]];
break;
}
}
return num;
}
-(CPFill *) barFillForBarPlot:(CPBarPlot *)barPlot recordIndex:(NSNumber *)index;
{
return nil;
}
@end
| 08iteng-ipad | examples/CPTestApp-iPhone-SpeedTest/Classes/CPTestAppBarChartController.m | Objective-C | bsd | 4,910 |
//
// main.m
// CPTestApp-iPad
//
// Created by Brad Larson on 4/1/2010.
//
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
| 08iteng-ipad | examples/CPTestApp-iPad/main.m | Objective-C | bsd | 309 |
//
// CPTestApp_iPadAppDelegate.h
// CPTestApp-iPad
//
// Created by Brad Larson on 4/1/2010.
//
#import <UIKit/UIKit.h>
@class CPTestApp_iPadViewController;
@interface CPTestApp_iPadAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
CPTestApp_iPadViewController *viewController;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet CPTestApp_iPadViewController *viewController;
@end
| 08iteng-ipad | examples/CPTestApp-iPad/Classes/CPTestApp_iPadAppDelegate.h | Objective-C | bsd | 462 |
//
// CPTestApp_iPadAppDelegate.m
// CPTestApp-iPad
//
// Created by Brad Larson on 4/1/2010.
//
#import "CPTestApp_iPadAppDelegate.h"
#import "CPTestApp_iPadViewController.h"
@implementation CPTestApp_iPadAppDelegate
@synthesize window;
@synthesize viewController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
return YES;
}
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
@end
| 08iteng-ipad | examples/CPTestApp-iPad/Classes/CPTestApp_iPadAppDelegate.m | Objective-C | bsd | 650 |