首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CGContext的问题

CGContext的问题
EN

Stack Overflow用户
提问于 2009-08-03 06:31:44
回答 1查看 491关注 0票数 0

当我触摸屏幕时,我想在UIView的矩形中画一条线。请谁能帮我检查一下代码!

代码语言:javascript
复制
- (void)drawRect:(CGRect)rect {
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 5.0);
    CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor);
    CGContextSetFillColorWithColor(context, [UIColor greenColor].CGColor);
    CGContextMoveToPoint(context, 100.0, 30.0);
    CGContextAddLineToPoint(context, 200.0, 30.0);
    CGContextStrokePath(context);
}
EN

回答 1

Stack Overflow用户

发布于 2010-08-08 16:16:08

只有当您在-drawRect:方法中时,UIGraphicsGetCurrentContext()才引用UIView的上下文。要在触摸屏幕时绘制一条线,需要使用一个变量来跟踪手指的状态。

代码语言:javascript
复制
@interface MyView : UIView {
   BOOL touchDown;
}
...

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
   touchDown = YES;
   [self setNeedsDisplay];
}
-(void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
   touchDown = NO;
   [self setNeedsDisplay];
}
-(void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event {
   touchDown = NO;
   [self setNeedsDisplay];
}

-(void)drawRect:(CGRect)rect {
   CGContextRef context = UIGraphicsGetCurrentContext();
   if(touchesDown) {
        CGContextSetLineWidth(context, 5.0);
        CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor);
        CGContextSetFillColorWithColor(context, [UIColor greenColor].CGColor);
        CGContextMoveToPoint(context, 100.0, 30.0);
        CGContextAddLineToPoint(context, 200.0, 30.0);
        CGContextStrokePath(context);
   }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1220891

复制
相关文章

相似问题

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