我正在实现一个包含 2 个 UIImageViews 的 CCLayer 子类。视图和图层的大小都相同:我用相同的框架初始化 UIImageViews,并将图层的 contentSize 设置为框架。一切工作正常,但似乎在绘图时第一点出现了问题。刚刚点击图像时没有跳线,但是当我尝试绘制笔画时,只要我移动手指,线的开头就会随机跳下(所以在这个截图中,我从左到右绘制除了对于左下角线)。我不确定我的代码哪里出错了:
//_drawImageView is the UIImageView I am drawing in.
#pragma mark - Touch Methods
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
penStroked = NO;
_prevPoint = [touch locationInView:[[CCDirector sharedDirector]view]];
CGRect rect = self.boundingBox;
if (CGRectContainsPoint(rect, _prevPoint)) {
return YES;
}
return NO;
}
- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
penStroked = YES;
_currPoint = [touch locationInView:_drawImageView];
UIGraphicsBeginImageContext(self.contentSize);
[_drawImageView.image drawInRect:CGRectMake(0, 0, _drawImageView.frame.size.width, _drawImageView.frame.size.height)];
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), _prevPoint.x, _prevPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), _currPoint.x, _currPoint.y);
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), penSize);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), penColor.r, penColor.g, penColor.b, 1.0);
CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeNormal);
CGContextStrokePath(UIGraphicsGetCurrentContext());
_drawImageView.image = UIGraphicsGetImageFromCurrentImageContext();
[_drawImageView setAlpha: penOpacity];
UIGraphicsEndImageContext();
_prevPoint = _currPoint;
}
最初我很难将绘制线的点与我手指的实际位置对齐,这就是为什么在 ccTouchBegan 方法中触摸取自 CCDirector 而在 ccTouchMoved 中取自_drawImageView。除了最初的不稳定行为之外,这是它似乎完美绘制的唯一方式。