【问题标题】:Drawing with CGContext使用 CGContext 绘图
【发布时间】:2014-08-06 00:54:22
【问题描述】:

我正在尝试通过touchesMove: 方法画线。

下面是我的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();

touchesMoved: 被调用;但是屏幕上什么也没有显示。

我错过了什么?

已添加

self 是 UIImageView 的子类。

【问题讨论】:

    标签: ios objective-c cgcontext


    【解决方案1】:

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

    这是我如何绘制的代码。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      相关资源
      最近更新 更多