我试图通过抚摸图像来画线,以通过CoreGraphics
框架产生类似刷子的效果。
我关注了这篇文章和这篇文章,并尝试从touchesMoved
方法中汲取灵感,代码示例将采用以下形式
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self.view];
UIImage *texture = [UIImage imageNamed:@"texture.png"];
CGPoint vector = CGPointMake(currentPoint.x - lastPoint.x, currentPoint.y - lastPoint.y);
NSLog(@" vector %@", NSStringFromCGPoint(vector));
CGFloat distance = hypotf(vector.x, vector.y);
vector.x /= distance;
vector.y /= distance;
for (CGFloat i = 0; i < distance; i += 1.0f) {
CGPoint p = CGPointMake(lastPoint.x + i * vector.x, lastPoint.y + i * vector.y);
[texture drawAtPoint:p blendMode:kCGBlendModeNormal alpha:1.0f];
NSLog(@"p %@", NSStringFromCGPoint(p));
}
previousPoint = currentPoint;
通过这样做,我收到了错误消息,
Jul 9 11:51:27 mac1.local Smooth Line View[1035] <Error>: CGContextSaveGState: invalid context 0x0
Jul 9 11:51:27 mac1.local Smooth Line View[1035] <Error>: CGContextSetBlendMode: invalid context 0x0
Jul 9 11:51:27 mac1.local Smooth Line View[1035] <Error>: CGContextSetAlpha: invalid context 0x0
Jul 9 11:51:27 mac1.local Smooth Line View[1035] <Error>: CGContextTranslateCTM: invalid context 0x0
Jul 9 11:51:27 mac1.local Smooth Line View[1035] <Error>: CGContextScaleCTM: invalid context 0x0
Jul 9 11:51:27 mac1.local Smooth Line View[1035] <Error>: CGContextDrawImage: invalid context 0x0
Jul 9 11:51:27 mac1.local Smooth Line View[1035] <Error>: CGContextRestoreGState: invalid context 0x0
所以,我把与上下文相关的代码放在上面,修改后的代码是
UITouch *touch = [touches anyObject];
currentPoint = [touch locationInView:self];
UIGraphicsBeginImageContext(self.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetBlendMode(context, kCGBlendModeNormal);
CGContextSetAlpha(context, 1.0f);
CGContextSaveGState(context);
UIImage *texture = [UIImage imageNamed:@"textureImg.png"];
[texture drawAtPoint:currentPoint blendMode:kCGBlendModeNormal alpha:1.0f];
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, 25.0);
CGContextSetRGBStrokeColor(context, texture.CGColor);
CGContextBeginPath(context);
CGContextMoveToPoint(context, previousPoint.x, previousPoint.y);
CGContextAddLineToPoint(context, currentPoint.x, currentPoint.y);
CGContextDrawPath(context, kCGPathFillStroke);
UIGraphicsEndImageContext();
但是当我跑步并尝试在触摸移动时绘制时,什么都没有绘制。我不明白出了什么问题。有人可以指出我的错误吗?我仍然花很多时间来解决这个问题,但现在还做不到。非常感谢任何及时的帮助。谢谢。