2011年6月19日 星期日

在 iPhone 上實現小畫家基本功能

.h

UIImageView *drawImage_;
CGPoint lastPoint_;

.m
-(id) init
{
if( (self=[super init])) {
        drawImage_ = [[[UIImageView alloc]initWithImage:nil]autorelease];
        drawImage_.frame = CGRectMake(0, 50, 320,400);
        [[[CCDirector sharedDirector]openGLView] addSubview:drawImage_];
        self.isTouchEnabled = YES;
}
return self;
}

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    lastPoint_ = [touch locationInView:drawImage_];    
}

- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint currentPoint = [touch locationInView:drawImage_];
    UIGraphicsBeginImageContext(drawImage_.frame.size);
    
    [drawImage_.image drawInRect:CGRectMake(0, 0, drawImage_.frame.size.width, drawImage_.frame.size.height)];
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound); 
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0,0.0,0.0, 1.0);
    CGContextBeginPath(UIGraphicsGetCurrentContext());
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint_.x, lastPoint_.y);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
    CGContextStrokePath(UIGraphicsGetCurrentContext());
    drawImage_.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    lastPoint_ = currentPoint;
}




沒有留言:

張貼留言