본문 바로가기

iOS개발팁

쿼츠2D 튜토리얼 - 간단한 도형 그리기


튜토리얼 진행 설명은 http://trailsinthesand.com/exploring-iphone-graphics-part-1/ 를 참고하세요 :)

: 예제코드 :
- (void)drawRect:(CGRect)rect
{
    //배경지우기
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextClearRect(ctx, rect);
   
    //빨간사각형 그리기
    CGContextSetRGBFillColor(ctx, 1.0, 0.0, 0.0, 1.0);
    CGContextFillRect(ctx, CGRectMake(10, 10, 50, 50));
   
    //녹색원 그리기
    CGContextSetRGBFillColor(ctx, 0.0, 1.0, 0.0, 1.0);
    CGContextFillEllipseInRect(ctx, CGRectMake(100, 100, 25, 25));
   
    //속이 빈 파란색 원 그리기
    CGContextSetRGBStrokeColor(ctx, 0.0, 0.0, 1.0, 1.0);
    CGContextStrokeEllipseInRect(ctx, CGRectMake(200, 200, 50, 50));
   
    //속이 빈 노란색 상자 그리기
    CGContextSetRGBStrokeColor(ctx, 1.0, 1.0, 0.0, 1.0);
    CGContextStrokeRect(ctx, CGRectMake(195, 195, 60, 60));
   
    //보라색 삼각형 그리기
    CGContextSetRGBStrokeColor(ctx, 1.0, 0.0, 1.0, 1.0);
    CGPoint points[6] = {
        CGPointMake(100, 200), CGPointMake(150, 250),
        CGPointMake(150, 250), CGPointMake(50, 250),
        CGPointMake(50, 250), CGPointMake(100, 200)
    };
    CGContextStrokeLineSegments(ctx, points, 6);
   
    //문자열 출력하기
    //문자열 출력은 좌표계가 뒤집어져 있기 때문에
    //y축 좌표를 반전시켜야 한다.
    char *text = "http://twitter.com/skyfe79";
    CGContextSelectFont(ctx, "Helvetica", 24.0, kCGEncodingMacRoman);
    CGContextSetTextDrawingMode(ctx, kCGTextFill);
    CGContextSetRGBFillColor(ctx, 0, 1.0, 1.0, 1.0);
   
    CGAffineTransform xform = CGAffineTransformMake(
                                                    1.0, 0.0,
                                                    0.0, -1.0,
                                                    0.0, 0.0);
    CGContextSetTextMatrix(ctx, xform);
    CGContextShowTextAtPoint(ctx, 10, 300, text, strlen(text));
   
    //다른 것 위에 투명 원 그리기
    CGContextSetRGBFillColor(ctx, 200, 200, 200, 0.5);
    CGContextFillEllipseInRect(ctx, CGRectMake(100, 200, 150, 150));
   
    //이미지 그리기
    NSString *imageFileName = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"imgimg.png"];
    CGDataProviderRef provider = CGDataProviderCreateWithFilename([imageFileName UTF8String]);
    CGImageRef image = CGImageCreateWithPNGDataProvider(provider, NULL, true, kCGRenderingIntentDefault);
    CGDataProviderRelease(provider);
   
    CGContextDrawImage(ctx, CGRectMake(200, 0, 100, 100), image);
    CGImageRelease(image);
}