Drawing with CGContext

蓝咒 提交于 2019-12-25 02:28:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!