devhkh

CGContextRef 정리

iOS2012. 3. 6. 10:59
우선 CGContextRef 는 UIView를 상속받은 클래스에서 사용되어야 한다.
일반 메소드에서 사용하려고 하면 사용할수 없다.


1. 객체 생성

CGContextRef context = UIGraphicsGetCurrentContext();



2. 그리기 시작

CGContextBeginPath(context);



3. 포인트(좌표) 이동 (x,y 좌표값을 설정하는데 다음번에 그리게 되면 이 좌표부터 그리게 된다.)

CGContextMoveToPoint(context, 160, 60);

 

4. 색상 설정

CGColorRef color = [UIColor redColor].CGColor;


그려야 할 객체 설정
4-1. 동그라미 설정

CGRect ellipseRect = CGRectMake(0, 0, 100, 100);

CGContextAddEllipseInRect(context, ellipseRect);



4-2. 라인그리기

CGContextMoveToPoint(context, 0, 0);

CGContextAddLineToPoint(context, 0, 40);

CGContextAddLineToPoint(context, 40, 40);

CGContextAddLineToPoint(context, 40, 0);

CGContextClosePath(context);

CGContextSetLineWidth(context, 2.0); 



5. 색상 채우기
5-1. 면 색상 설정 

CGContextSetFillColorWithColor(context, color);



5-2. 라인 색상 설정

CGContextSetStrokeColorWithColor(context, color);



6. 그리기 (주석을 참고하여 3개중에 한개만 사용한다.)

CGContextDrawPath(context, kCGPathFill);                       //채워서 그리기

CGContextDrawPath(context, kCGPathStroke);                     //테두리만 그리기
CGContextDrawPath(context, kCGPathFillStroke);                 //테두리와 채우기 그리기




참고 소스 (하트그리기)

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextBeginPath(context);

CGContextMoveToPoint(context, 160, 60);

CGContextAddCurveToPoint(context, 

                         250, 10

                         220, 150

                         160, 160);


CGContextAddCurveToPoint(context, 

                         90, 150

                         60, 10

                         160, 60);

CGColorRef color = [UIColor redColor].CGColor;

CGContextSetFillColorWithColor(context, color);

CGContextClosePath(context);    

    

CGContextDrawPath(context, kCGPathFillStroke);



아래와 같이 예쁜(?) 하트가 그려진다.









  

'iOS' 카테고리의 다른 글

APNS 사용  (0) 2012.03.12
장면이동시 애니메이션 주기  (0) 2012.03.06
이미지 테두리를 둥글게 깍는 방법  (0) 2012.02.28
NSUserDefaults 사용하기  (0) 2012.02.20
현재 접속된 wifi의 ssid를 알아오는 방법  (0) 2012.02.01