问题
I'm trying to draw lines through touchesMove:
method.
Below is my touchesMoved:
.
UIGraphicsBeginImageContext(self.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
// context setting
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineJoin(context, kCGLineJoinRound);
CGContextSetLineWidth(context, 2.0);
CGContextSetRGBStrokeColor(context, 255, 0, 0, 0.5);
CGContextSetBlendMode(context, kCGBlendModeNormal);
// drawing
CGContextMoveToPoint(context, lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(context, currentPoint.x, currentPoint.y);
CGContextStrokePath(context);
CGContextFlush(context);
self.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
The touchesMoved:
is invoked; However nothing is shown on the screen.
What am I missing?
Added
self is a subclass of UIImageView.
回答1:
OK, I found why it wasn't working. I created CGContext
every touch move event. I moved the line UIGraphicsBeginImageContext(self.frame.size);
to init
method and UIGraphicsEndImageContext();
to dealloc
.
Here's the code how I drawing.
static CGPoint lastPoint;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch_ = [touches anyObject];
CGPoint point_ = [touch_ locationInView:self];
lastPoint = point_;
CGContextRef context = UIGraphicsGetCurrentContext();
// context setting
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineJoin(context, kCGLineJoinRound);
CGContextSetLineWidth(context, 2.0);
CGContextSetRGBStrokeColor(context, 255, 0, 0, 0.5);
CGContextSetBlendMode(context, kCGBlendModeNormal);
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
lastPoint = CGPointZero;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self];
CGContextRef context = UIGraphicsGetCurrentContext();
// drawing
CGContextMoveToPoint(context, lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(context, currentPoint.x, currentPoint.y);
CGContextStrokePath(context);
CGContextFlush(context);
self.image = UIGraphicsGetImageFromCurrentImageContext();
lastPoint = currentPoint;
}
来源:https://stackoverflow.com/questions/25150674/drawing-with-cgcontext