Computer Science/ios

muaic chart

728x90
반응형


//  TestStoryboard

//

//  Created by SWU CSE on 12. 11. 13..

//  Copyright (c) 2012 Apple10. All rights reserved.

//


#import "RootViewController.h"

@interface RootViewController ()

@end

@implementation RootViewController


- (void)viewDidLoad{

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];

    [self initCoreData];

    [self performFetch];

    


}

- (void)viewDidUnload{

    [super viewDidUnload];

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{

    return (interfaceOrientation == UIInterfaceOrientationPortrait);

}


#pragma mark Table

// Table Section

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

return [[fetchedResultsController sections] count];

}

// Section Cell & 내용

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

return [[[fetchedResultsController sections] objectAtIndex:section] numberOfObjects];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    // Create a cell

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"music cell"];

if (!cell) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"music cell"];


    

    

// Recover object from fetched results

NSManagedObject *managedObject = [fetchedResultsController objectAtIndexPath:indexPath];

cell.textLabel.text = [managedObject valueForKey:@"mName"];

    

    // UIColor *color = [self getColor:[managedObject valueForKey:@"color"]];

    // cell.textLabel.textColor = ([[managedObject valueForKey:@"color"] hasPrefix:@"FFFFFF"]) ? [UIColor blackColor] : color;

    return cell;

}




//  Table Title

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)aTableView{

    return [fetchedResultsController sectionIndexTitles];

}

- (NSString *)tableView:(UITableView *)aTableView titleForHeaderInSection:(NSInteger)section{

NSArray *titles = [fetchedResultsController sectionIndexTitles];

if (titles.count <= section) return @"Error";

return [titles objectAtIndex:section];

}




- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{

    return NO; // no reordering allowed

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    // NSManagedObject *managedObject = [fetchedResultsController objectAtIndexPath:indexPath];

    // UIColor *color = [self getColor:[managedObject valueForKey:@"color"]];

    // self.navigationController.navigationBar.tintColor = color;

}








//------------------------------------Music엔티티에서 속성 가져오기

- (void) initCoreData

{

NSError *error;

// Path to sqlite file.

NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/datamusic.sqlite"];

NSURL *url = [NSURL fileURLWithPath:path];

    BOOL needsBuilding = ![[NSFileManager defaultManager] fileExistsAtPath:path];

// Init the model, coordinator, context

NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];

NSPersistentStoreCoordinator *persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];

    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error])

NSLog(@"Error: %@", [error localizedFailureReason]);

else

{

context = [[NSManagedObjectContext alloc] init];

[context setPersistentStoreCoordinator:persistentStoreCoordinator];

}

    

    // Create the DB from the text file if needed

    if (needsBuilding){

NSString *pathname =[[NSBundle mainBundle]pathForResource:@"Music"ofType:@"txt"];

NSArray *musics = [[NSString stringWithContentsOfFile:pathname encoding:NSUTF8StringEncoding error:nil]componentsSeparatedByString:@"\n"];

for (NSString *musicString in musics)

            [self addMusicFileToDB:musicString];

}

     

}

- (void) addMusicFileToDB: (NSString *) musicString{

NSError *error;

// Extract the color/name pair

NSArray *musicComponents = [musicString componentsSeparatedByString:@"#"];

if (musicComponents.count != 3)

        return;

// Store a name/color pair into the database

Music *item = (Music *)[NSEntityDescription insertNewObjectForEntityForName:@"MusicValue"inManagedObjectContext:context];

item.mStyle = [musicComponents objectAtIndex:2];

    item.mColor = [musicComponents objectAtIndex:1];

item.mName = [musicComponents objectAtIndex:0];

    

item.mSection = [[item.mName substringToIndex:1] uppercaseString];

if (![context save:&error])

        NSLog(@"Error: %@", [error localizedFailureReason]);

}

- (void) performFetch

{

// Init a fetch request

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription *entity = [NSEntityDescription entityForName:@"MusicValue"inManagedObjectContext:context];

[fetchRequest setEntity:entity];

[fetchRequest setFetchBatchSize:100];

// mName 기준으로 정렬

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"mName" ascending:YES selector:nil];

NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor];

[fetchRequest setSortDescriptors:descriptors];

    

// fetchedResultsController 이용

NSError *error;

fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:@"mSection" cacheName:nil];

   // fetchedResultsController.delegate = self;

    [fetchedResultsController performFetch:&error];

    

//-------------------------------------------------------------

    for (Music *music in fetchedResultsController.fetchedObjects)

        NSLog(@"NAME : %@ STYLE : %@ SECTION : %@", music.mName, music.mStyle, music.mSection);

    

    NSArray *objects = [context executeFetchRequest:fetchRequest error:&error];

    NSLog(@"count : %@", [NSString stringWithFormat:@"%d matches found", [objects count]]);

    

    NSPredicate *pred = [NSPredicate predicateWithFormat:@"(mStyle = %@)", @"1"];

    [fetchRequest setPredicate:pred];


    NSArray *matchedobjects = [context executeFetchRequest:fetchRequest error:&error];

    NSManagedObject *MO = [matchedobjects objectAtIndex:0];

    NSLog(@"count : %@", [NSString stringWithFormat:@"%d matches found", [matchedobjects count]]);

    NSLog(@"name : %@", [MO valueForKey:@"mName"]);

    


    

    

    

}



/*

 - (UIColor *) getColor: (NSString *) hexColor{

 // Convert a hex color string into a UIColor instance

 unsigned int red, green, blue;

 NSRange range;

 range.length = 2;

 range.location = 0;

 [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&red];

 range.location = 2;

 [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&green];

 range.location = 4;

 [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&blue];

 return [UIColor colorWithRed:(float)(red/255.0f) green:(float)(green/255.0f) blue:(float)(blue/255.0f) alpha:1.0f];

 }

 */

@end



//

//  LPGlobal.m

//  BarChart

//

//  Created by Park Jong Pil on 11. 7. 25..

//  Copyright 2011 Reciper. All rights reserved.

//


#import "LPGlobal.h"


// 박스 1픽셀 스토로크.

CGRect rectFor1PxStroke(CGRect rect) 

{

    return CGRectMake(rect.origin.x + 0.5, rect.origin.y + 0.5, rect.size.width - 1, rect.size.height - 1);

}


// 라이너 그라디언트.

void drawLinearGradient(CGContextRef context, CGRect rect, CGColorRef startColor, CGColorRef  endColor) 

{

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    CGFloat locations[] = { 0.0, 1.0 };

    

    NSArray *colors = [NSArray arrayWithObjects:(__bridge id)startColor, (__bridge id)endColor, nil];

    

    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)colors, locations);

    

    CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));

    CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));

    

    CGContextSaveGState(context);

    CGContextAddRect(context, rect);

    CGContextClip(context);

    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);

    CGContextRestoreGState(context);

    

    CGGradientRelease(gradient);

}


// 1픽셀 스트로크.

void draw1PxStroke(CGContextRef context, CGPoint startPoint, CGPoint endPoint, CGColorRef color) 

{

    CGContextSaveGState(context);

    CGContextSetLineCap(context, kCGLineCapSquare);

    CGContextSetStrokeColorWithColor(context, color);

    CGContextSetLineWidth(context, 1.0);

    CGContextMoveToPoint(context, startPoint.x + 0.5, startPoint.y + 0.5);

    CGContextAddLineToPoint(context, endPoint.x + 0.5, endPoint.y + 0.5);

    CGContextStrokePath(context);

    CGContextRestoreGState(context);        

}


// 글로스와 그라디언트.

void drawGlossAndGradient(CGContextRef context, CGRect rect, CGColorRef startColor, CGColorRef endColor) 

{

    drawLinearGradient(context, rect, startColor, endColor);

    

    CGColorRef glossColor1 = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.35].CGColor;

    CGColorRef glossColor2 = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.1].CGColor;

    

    CGRect topHalf = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height/2);

    

    drawLinearGradient(context, topHalf, glossColor1, glossColor2);

}


// 아크.

CGMutablePathRef createArcPathFromBottomOfRect(CGRect rect, CGFloat arcHeight) 

{

    CGRect arcRect = CGRectMake(rect.origin.x, rect.origin.y + rect.size.height - arcHeight, 

                                rect.size.width, arcHeight);

    

    CGFloat arcRadius = (arcRect.size.height/2) + (pow(arcRect.size.width, 2) / (8*arcRect.size.height));

    CGPoint arcCenter = CGPointMake(arcRect.origin.x + arcRect.size.width/2, arcRect.origin.y + arcRadius);

    

    CGFloat angle = acos(arcRect.size.width / (2*arcRadius));

    CGFloat startAngle = radians(180) + angle;

    CGFloat endAngle = radians(360) - angle;

    

    CGMutablePathRef path = CGPathCreateMutable();

    CGPathAddArc(path, NULL, arcCenter.x, arcCenter.y, arcRadius, startAngle, endAngle, 0);

    CGPathAddLineToPoint(path, NULL, CGRectGetMaxX(rect), CGRectGetMinY(rect));

    CGPathAddLineToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMinY(rect));

    CGPathAddLineToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMaxY(rect));

    return path;    

}


// 라운드 박스.

CGMutablePathRef createRoundedRectForRect(CGRect rect, CGFloat radius) 

{

    CGMutablePathRef path = CGPathCreateMutable();

    CGPathMoveToPoint(path, NULL, CGRectGetMidX(rect), CGRectGetMinY(rect));

    CGPathAddArcToPoint(path, NULL, CGRectGetMaxX(rect), CGRectGetMinY(rect), 

CGRectGetMaxX(rect), CGRectGetMaxY(rect), radius);

    CGPathAddArcToPoint(path, NULL, CGRectGetMaxX(rect), CGRectGetMaxY(rect), 

CGRectGetMinX(rect), CGRectGetMaxY(rect), radius);

    CGPathAddArcToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMaxY(rect), 

CGRectGetMinX(rect), CGRectGetMinY(rect), radius);

    CGPathAddArcToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMinY(rect), 

CGRectGetMaxX(rect), CGRectGetMinY(rect), radius);

    CGPathCloseSubpath(path);

    return path;        

}


// 라운드 박스.

CGPathRef createRoundedRectPath(CGRect rect, CGFloat cornerRadius) 

{

CGMutablePathRef path;

path = CGPathCreateMutable();

double maxRad = MAX(CGRectGetHeight(rect) / 2., CGRectGetWidth(rect) / 2.);

    

if (cornerRadius > maxRad) cornerRadius = maxRad;

CGPoint bl, tl, tr, br;

bl = tl = tr = br = rect.origin;

tl.y += rect.size.height;

tr.y += rect.size.height;

tr.x += rect.size.width;

br.x += rect.size.width;

CGPathMoveToPoint(path, NULL, bl.x + cornerRadius, bl.y);

CGPathAddArcToPoint(path, NULL, bl.x, bl.y, bl.x, bl.y + cornerRadius, cornerRadius);

CGPathAddLineToPoint(path, NULL, tl.x, tl.y - cornerRadius);

CGPathAddArcToPoint(path, NULL, tl.x, tl.y, tl.x + cornerRadius, tl.y, cornerRadius);

CGPathAddLineToPoint(path, NULL, tr.x - cornerRadius, tr.y);

CGPathAddArcToPoint(path, NULL, tr.x, tr.y, tr.x, tr.y - cornerRadius, cornerRadius);

CGPathAddLineToPoint(path, NULL, br.x, br.y + cornerRadius);

CGPathAddArcToPoint(path, NULL, br.x, br.y, br.x - cornerRadius, br.y, cornerRadius);

CGPathCloseSubpath(path);

CGPathRef ret;

ret = CGPathCreateCopy(path);

CGPathRelease(path);

    

return ret;

}




//

//  BarPlot.h

//  BarChart

//

//  Created by Park Jong Pil on 11. 7. 25..

//  Copyright 2011 Reciper. All rights reserved.

//


#import <UIKit/UIKit.h>


@interface BarPlot : UIView

{

    

}


@property (nonatomic, retain) UIColor *barColor;

@property (nonatomic, retain) UIColor *barBgColor;


@end



//

//  BarPlot.m

//  BarChart

//

//  Created by Park Jong Pil on 11. 7. 25..

//  Copyright 2011 Reciper. All rights reserved.

//


#import "BarPlot.h"


@implementation BarPlot


@synthesize barColor;

@synthesize barBgColor;


- (id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self

    {

        // Initialization code

        self.barBgColor = [UIColor whiteColor];

    }

    return self;

}


// Only override drawRect: if you perform custom drawing.

// An empty implementation adversely affects performance during animation.

- (void)drawRect:(CGRect)rect

{

    // 컨텍스트.

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, self.barBgColor.CGColor);

    CGContextFillRect(context, rect);

    

    CGRect inRect = CGRectMake(rect.origin.x + 1.5, rect.origin.y + 1.5, rect.size.width - 3, rect.size.height - 3);

    CGContextSetFillColorWithColor(context, self.barColor.CGColor);

    CGContextFillRect(context, inRect);

}


@end



//

//  BarChartView.h

//  BarChart

//

//  Created by Park Jong Pil on 11. 7. 25..

//  Copyright 2011 Reciper. All rights reserved.

//


#import <UIKit/UIKit.h>



@interface BarChartComponent : NSObject

{

    NSString *xValue;

    float yValue;

}


@property (nonatomic, retain) NSString *xValue;//발라드

@property (nonatomic, assign) float yValue;


@end



#define X_LABEL_COUNT 10

#define Y_LABEL_COUNT 10


@interface BarChartView : UIView

{

    CGRect xLabelFrame[X_LABEL_COUNT];

    UILabel *xLabelForFrame[X_LABEL_COUNT];

    

    CGRect yLabelFrame[Y_LABEL_COUNT];

    UILabel *yLabelForFrame[Y_LABEL_COUNT];

}


@property (nonatomic, retain) NSMutableArray *components;

@property (nonatomic, retain) UIView *plotBackground;

@property (nonatomic, retain) NSMutableArray *colors;


- (void)drawLine:(CGContextRef)context;

- (void)createXLabel;

- (void)createYLabel;

- (float)calcMaxValue;


@end




//

//  BarChartView.m

//  BarChart

//

//  Created by Park Jong Pil on 11. 7. 25..

//  Copyright 2011 Reciper. All rights reserved.

//


#import "BarChartView.h"

#import "LPGlobal.h"

#import "BarPlot.h"

#import "AppDelegate.h"


@implementation BarChartComponent


@synthesize xValue;

@synthesize yValue;


@end



#define LINE_HEIGHT_MARGIN 22.5 //배경축 시작높이

#define X_LABEL_WIDTH_MARGIN 40.0 //x 레이블 간격

#define Y_LABEL_HEIGHT_MARGIN 22.5 //y 레이블 간격

#define BAR_MAX_HEIGHT 200.0 // 최대높이

#define BAR_BASE_Y 225.0 // 시작위치

#define BAR_WIDTH 8.0 // 넓이

#define BAR_MARGIN 32.0 // 간격

//#define CURRENCY_UNIT 100


#define FIRST_COLOR UIColorFromRGB(0xe07e59)

#define SECOND_COLOR UIColorFromRGB(0x9ac05b)

#define THIRD_COLOR UIColorFromRGB(0xecbd3d)

#define FOURTH_COLOR UIColorFromRGB(0x67defc)

#define FIFTH_COLOR UIColorFromRGB(0x7981cd)

#define SIXTH_COLOR UIColorFromRGB(0xecbd3d)

#define SEVENTH_COLOR UIColorFromRGB(0xe07e59)

#define EIGHTH_COLOR UIColorFromRGB(0x67defc)

#define NINTH_COLOR UIColorFromRGB(0x7981cd)

#define TENTH_COLOR UIColorFromRGB(0x9ac05b)


@implementation BarChartView


@synthesize components;

@synthesize plotBackground;

@synthesize colors;



- (id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self

    {

        // Initialization code

        self.colors = [NSMutableArray arrayWithObjects:

                       FIRST_COLOR

                       SECOND_COLOR

                       THIRD_COLOR

                       FOURTH_COLOR

                       FIFTH_COLOR,

                       SIXTH_COLOR,

                       SEVENTH_COLOR,

                       EIGHTH_COLOR,

                       NINTH_COLOR,

                       TENTH_COLOR,nil];

        

        [self createXLabel];

        [self createYLabel];

        



        

    }

    return self;

}


// Only override drawRect: if you perform custom drawing.

// An empty implementation adversely affects performance during animation.

- (void)drawRect:(CGRect)rect

{

    // 컨텍스트.

    CGContextRef context = UIGraphicsGetCurrentContext();

    

    [self drawLine:context];

    

    self.plotBackground = [[UIView alloc] initWithFrame:CGRectMake(0.0, 300.0, 480.0, 0.0)];

    self.plotBackground.backgroundColor = [UIColor clearColor];

    self.plotBackground.clipsToBounds = YES;

    [self addSubview:self.plotBackground];

    

    

    // 차트 그리기.

    if ([self.components count] > 0)

    {

        // Y 최대값.

        float maxY = [self calcMaxValue];

        

        for (int i = 0; i < [self.components count]; i++)

        {

            

            BarChartComponent *component = [self.components objectAtIndex:i];

            

            

            

            //db

            AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];

            

            


            if(i==0){

                component.yValue = [delegate.music1YValue floatValue];

            }else if (i==1){

                component.yValue = [delegate.music2YValue floatValue];

            }    else if (i==2){

                component.yValue = [delegate.music3YValue floatValue];

            }    else if (i==3){

                component.yValue = [delegate.music4YValue floatValue];

            }    else if (i==4){

                component.yValue = [delegate.music5YValue floatValue];

            }    else if (i==5){

                component.yValue = [delegate.music6YValue floatValue];

            }    else if (i==6){

                component.yValue = [delegate.music7YValue floatValue];

            }    else if (i==7){

                component.yValue = [delegate.music8YValue floatValue];

            }    else if (i==8){

                component.yValue = [delegate.music9YValue floatValue];

            }    else {

                component.yValue = [delegate.music10YValue floatValue];

            }


           // 

           

            //

            

            

            

            // 바의 높이 계산.

            

            float barHeight = (200 *component.yValue) / maxY;

            NSLog(@">>>>>>>>>%f", barHeight);

            

            // 바의 프레임.

            CGRect barRect = CGRectMake(60.0 + ((BAR_WIDTH + BAR_MARGIN) * i),

                                        (BAR_BASE_Y - barHeight), 

                                        BAR_WIDTH, barHeight);

            

            BarPlot *barPlot = [[BarPlot alloc] initWithFrame:barRect];

            barPlot.barColor = [self.colors objectAtIndex:i];

            [self.plotBackground addSubview:barPlot];


            NSString *XLabelText = component.xValue;

            xLabelForFrame[i].text = XLabelText;            

            CGSize XLabelSize = [XLabelText sizeWithFont:[UIFont systemFontOfSize:xLabelForFrame[i].font.pointSize]];

            xLabelForFrame[i].frame = CGRectMake(xLabelForFrame[i].frame.origin.x, xLabelForFrame[i].frame.origin.y, XLabelSize.width, XLabelSize.height);

            

            NSString *YLabelText = @"[ Music Recommend ]";

            yLabelForFrame[1].text = YLabelText;

            CGSize YLabelSize = [YLabelText sizeWithFont:[UIFont systemFontOfSize:yLabelForFrame[1].font.pointSize]];

            yLabelForFrame[1].frame = CGRectMake(yLabelForFrame[1].frame.origin.x, yLabelForFrame[1].frame.origin.y, YLabelSize.width, YLabelSize.height);

        }

        

    }

    

    // 애니메이션.

    [UIView beginAnimations:nil context:nil];

    [UIView setAnimationDuration:1.1];

    [UIView setAnimationDelegate:self];

    self.plotBackground.frame = CGRectMake(0.0, 0.0, 480.0, 250.0);

    [UIView commitAnimations];

}


// 백그라운드 라인 디자인.

- (void)drawLine:(CGContextRef)context

{

    // 라인 컬러 설정.

CGColorRef lineColor = RGB(222, 222, 222).CGColor;

    

// 수평선 그리기.

    for (int i = 0; i < Y_LABEL_COUNT; i++) 

    {

        // 위치.

        CGPoint startPoint = CGPointMake(35.0, 25.0 + (LINE_HEIGHT_MARGIN * i));

        CGPoint endPoint = CGPointMake(450.0, 25.0 + (LINE_HEIGHT_MARGIN * i));

        

        if (i != 9)

        {

            draw1PxStroke(context, startPoint, endPoint, lineColor);

        }

        else

        { 

            CGContextSetStrokeColorWithColor(context, lineColor);

            CGContextSetLineWidth(context, 4.0f);

            CGContextMoveToPoint(context, startPoint.x, startPoint.y);

            CGContextAddLineToPoint(context, endPoint.x, endPoint.y);

            CGContextStrokePath(context);

        }

    }

    

    // 수직선 그리기.

    CGPoint startPoint = CGPointMake(35.0, 17.0);

    CGPoint endPoint = CGPointMake(35.0, 230.0);

    draw1PxStroke(context, startPoint, endPoint, lineColor);

}


// X 라벨 디자인.

- (void)createXLabel

{

    for (int i = 0; i < X_LABEL_COUNT; i++)

    {

        int index = i;

        CGRect frame = CGRectMake(50.0 + (X_LABEL_WIDTH_MARGIN * i), 235.0, X_LABEL_WIDTH_MARGIN, 10.0);

        xLabelFrame[index] = frame;

        UILabel *xLabel = [[UILabel alloc] init];

        

        xLabelForFrame[index] = xLabel;

        xLabel.frame = frame;

        xLabel.tag = index;

        xLabel.backgroundColor = [UIColor clearColor];

        xLabel.font = [UIFont systemFontOfSize:10.5];

        xLabel.textAlignment = UITextAlignmentCenter;

        xLabel.textColor = [UIColor grayColor];

        

        [self addSubview:xLabel];


    }

}


// Y 라벨 디자인.

- (void)createYLabel

{

    for (int i = 0; i < Y_LABEL_COUNT; i++)

    {

        int index = i;

        

        CGRect frame = CGRectMake(50.0, 2.0 + (Y_LABEL_HEIGHT_MARGIN * i), 65.0, 0.0);

        

        yLabelFrame[index] = frame;

        UILabel *yLabel = [[UILabel alloc] init];

        yLabelForFrame[index] = yLabel;


        yLabel.frame = frame;

        yLabel.tag = index;

        yLabel.backgroundColor = [UIColor clearColor];

        yLabel.font = [UIFont systemFontOfSize:20];

        yLabel.textAlignment = UITextAlignmentRight;

        yLabel.textColor = [UIColor darkGrayColor];

        [self addSubview:yLabel];


    }

}


// Y 최대값 계산.

- (float)calcMaxValue

{

    NSMutableArray *numberArray = [NSMutableArray array];

    for (BarChartComponent *component in self.components)

    {

        [numberArray addObject:[NSNumber numberWithFloat:component.yValue]];

    }

    

    // 배열에서 최대값.

    float highestNumber = 0.0;

    int numberIndex = 0;

    for (NSNumber *theNumber in numberArray)

    {

        if ([theNumber floatValue] > highestNumber) 

        {

            highestNumber = [theNumber integerValue];

            numberIndex = [numberArray indexOfObject:theNumber];

        }

    }

    

    return highestNumber;

}


@end




//

//  BarChartViewController.h

//  BarChart

//

//  Created by Park Jong Pil on 11. 7. 25..

//  Copyright 2011 Reciper. All rights reserved.

//


#import <UIKit/UIKit.h>

#import "LPGlobal.h"


@class BarChartView;


@interface ChartViewController : UIViewController <UIScrollViewDelegate>


@property (nonatomic, retain) NSArray *data;

@property (nonatomic, retain) BarChartView *barChart;


- (NSMutableArray *)loadData;


@end




//

//  BarChartViewController.m

//  BarChart

//

//  Created by Park Jong Pil on 11. 7. 25..

//  Copyright 2011 Reciper. All rights reserved.

//


#import "ChartViewController.h"

#import "BarChartView.h"



@implementation ChartViewController


@synthesize data;

@synthesize barChart;


- (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.

}


#pragma mark - View lifecycle


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad

{

    [super viewDidLoad];

    

    // 데이터.

    self.data = [self loadData];

    

    // 차트 .

    self.barChart = [[BarChartView alloc] initWithFrame:CGRectMake(0.0, 0.0, 480.0, 400.0)];

    self.barChart.backgroundColor = RGB(247, 247, 247);

    [self.view addSubview:barChart];

    

    NSMutableArray *components = [NSMutableArray array];

    for (int i = 0; i < [self.data count]; i++)

    {

        NSDictionary *dict = [self.data objectAtIndex:i];

        BarChartComponent *component = [[BarChartComponent alloc] init];

        component.xValue = [dict objectForKey:@"xValue"];

        component.yValue = [[dict objectForKey:@"yValue"] floatValue];

        

        [components addObject:component];

    }

    [barChart setComponents:components];

}


- (void)viewDidUnload

{

    [super viewDidUnload];

    // Release any retained subviews of the main view.

    // e.g. self.myOutlet = nil;

}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

{

    // Return YES for supported orientations

    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);

}




#pragma mark - 커스텀 메서드


// 샘플 데이터 로드.

- (NSMutableArray *)loadData

{

    NSString *path = [[NSBundle mainBundle] pathForResource:@"DataMusic" ofType:@"plist"];

NSMutableArray *sampleData = [[NSMutableArray alloc] initWithContentsOfFile:path];

    

return sampleData;

}


@end


728x90
반응형