首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用CGContext绘图

用CGContext绘图
EN

Stack Overflow用户
提问于 2014-08-06 00:54:22
回答 1查看 1K关注 0票数 0

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

下面是我的touchesMoved:

代码语言:javascript
复制
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的一个子类。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-06 01:20:39

好吧,我知道为什么它不起作用了。我创建了CGContext每一个触摸移动事件。我将行UIGraphicsBeginImageContext(self.frame.size);移到init方法,将UIGraphicsEndImageContext();移到dealloc

这是我画的代码。

代码语言:javascript
复制
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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25150674

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档