아이폰에서 챠트 또는 그래프를 그려야 하는 경우가 종종 있다. 개인적으로 만드는거라면 오픈소스를 가져다 쓰는게 가장 편하지만 디자인너의 요구사항이 까다롭다면 어쩔수 없이 직접 그려줘야 한다.
그리는 방법은 다음과 같은 순서로 작성한다.
1. UIView를 상속받은 차트용 뷰를 작성
2. 제대로 만들었다면 주석처리된 drawRect 메소드가 나오는데 이걸 주석을 해제.
3. drawRect메소드에 그리고 싶은 코드를 넣어줌
*참고로 drawRect메소드는 첫 화면에 뿌려질때 불려지는 콜백함수이다.
인위적으로 불러줘야 할 경우에는 setNeedDisplay라는 메소드를 호출해 준다.
그릴때 자주쓰는 기본적인 메소드를 만들어 실장해 보았다.
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
CGContextRef ctx = UIGraphicsGetCurrentContext();
[self drawLine:ctx
color:[UIColor grayColor]
width:1.0f
startPoint:CGPointMake(10, 20)
endPoint:CGPointMake(100, 40)];
[self drawCircle:ctx
fillColor:[UIColor blackColor]
strokeColor:[UIColor grayColor]
radius:30.0f
CenterPoint:CGPointMake(250, 40)];
[self drawText:ctx text:@"Graph TEST!!" size:13.0f point:CGPointMake(100, 100)];
}
- (void)drawLine:(CGContextRef)ctx color:(UIColor *)c width:(float)w startPoint:(CGPoint)sp endPoint:(CGPoint)ep {
CGContextSetStrokeColorWithColor(ctx, c.CGColor);
CGContextBeginPath(ctx);
CGContextMoveToPoint(ctx, sp.x, sp.y);
CGContextAddLineToPoint(ctx, ep.x, ep.y);
CGContextStrokePath(ctx);
}
- (void)drawCircle:(CGContextRef)ctx fillColor:(UIColor *)fc strokeColor:(UIColor *)sc radius:(float)r CenterPoint:(CGPoint)cp {
// Set the width of the line
CGContextSetLineWidth(ctx, 2.0);
//Make the circle
// 150 = x coordinate
// 150 = y coordinate
// 100 = radius of circle
// 0 = starting angle
// 2*M_PI = end angle
// YES = draw clockwise
CGContextBeginPath(ctx);
CGContextAddArc(ctx, cp.x, cp.y, r, 0, 2*M_PI, YES);
CGContextClosePath(ctx);
//color
CGContextSetFillColorWithColor(ctx, fc.CGColor);
CGContextSetStrokeColorWithColor(ctx, sc.CGColor);
// Note: If I wanted to only stroke the path, use:
// CGContextDrawPath(context, kCGPathStroke);
// or to only fill it, use:
// CGContextDrawPath(context, kCGPathFill);
//Fill/Stroke the path
CGContextDrawPath(ctx, kCGPathFillStroke);
}
- (void)drawCircle:(CGContextRef)ctx color:(UIColor *)c radius:(float)r CenterPoint:(CGPoint)cp {
[self drawCircle:ctx fillColor:c strokeColor:c radius:r CenterPoint:cp];
}
- (void)drawText:(CGContextRef)ctx text:(NSString *)t size:(float)s point:(CGPoint)p {
CGContextSetTextDrawingMode(ctx, kCGTextFill); // This is the default
[[UIColor redColor] setFill]; // This is the default
[t drawAtPoint:CGPointMake(p.x, p.y)
withAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Helvetica"
size:s]}];
}
출력결과
'코딩(プログラミング)' 카테고리의 다른 글
Objective-C에서 NSData의 형변환 (0) | 2014.04.30 |
---|---|
Objective-c KVO 샘플 구현하기 (0) | 2014.04.07 |
아이폰에서 차트나 그래프를 그릴려면? (0) | 2014.03.29 |
AutoLayout 에서 frame조정이 안되는 문제 해결방법 (스크롤뷰 문제포함) (0) | 2014.03.08 |
맥에서 구글앱엔진 파이썬 개발환경설정 (2) | 2014.02.02 |
iphone개발에 필요한 sqlite 명령어 (0) | 2013.12.23 |
댓글을 달아 주세요