Ios 使用CGContext绘制

Ios 使用CGContext绘制,ios,objective-c,cgcontext,Ios,Objective C,Cgcontext,我试图通过触摸移动:方法来画线 下面是我的触摸移动: UIGraphicsBeginImageContext(self.frame.size); CGContextRef context = UIGraphicsGetCurrentContext(); // context setting CGContextSetLineCap(context, kCGLineCapRound); CGContextSetLineJoin(context, kCGLineJoinRound); CGConte

我试图通过
触摸移动:
方法来画线

下面是我的
触摸移动:

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();
调用
触摸移动:
;但是,屏幕上没有显示任何内容

我错过了什么

已添加


self是UIImageView的一个子类。

好的,我找到了它不起作用的原因。我创建了
CGContext
每次触摸移动事件。我移动了行
UIGraphicsBeginImageContext(self.frame.size)
init
方法和
UIGraphicsEndImageContext()
解除锁定

这是我如何画画的代码

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;
}