본문 바로가기
프로그래밍/iOS

uiimageview위에 그림 그리기

by 백룡화검 2012. 1. 12.
헤더파일
@interface CustomView: UIViewController
{
    UIImageView *drawImage;
    CGPoint lastPoint;
    CGPoint currentPoint;
}
// xib파일과 연결된 UIImagView의 프라퍼티 
@property (strong, nonatomic) IBOutlet UIImageView *drawImageView;
@end

.m파일
// Override메서드

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {


    NSLog(@"touch began");

    UITouch *touch = [touches anyObject];


    // 3 터치하면 이미지 초기화

    if ([touch tapCount] == 3) {

        drawImage.image = nil;

        return;

    }

    lastPoint = [touch locationInView:self.drawImageView];

}

// Override메서드

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    

    NSLog(@"touch move");

    UITouch *touch = [touches anyObject];   

    currentPoint = [touch locationInView:self.drawImageView];

    

    UIGraphicsBeginImageContext(self.drawImageView.frame.size);

    [drawImage.image drawInRect:CGRectMake(0, 0, self.drawImageView.frame.size.width, self.drawImageView.frame.size.height)];

    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);

    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);

    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.1, 0.1, 0.1, 1.0);

    CGContextBeginPath(UIGraphicsGetCurrentContext());

    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);

    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);

    CGContextStrokePath(UIGraphicsGetCurrentContext());

    drawImage.image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    

    lastPoint = currentPoint;


}