Ios 如何使用核心图形在触摸位置绘制圆形?
新来的程序员。我在尝试使用核心图形在触摸位置周围绘制笔划弧时遇到问题。我有画圆圈的方法工作得很好,当我点击屏幕时,我已经测试并正在注册触摸,但是当我尝试调用该方法在点击时画圆圈时,我得到错误“CGContextBlahBlah:invalid context 0x0” 我想这是因为我没有调用drawRect()中的方法 那么我怎样才能在触摸屏上调用这个方法呢?此外,如何在绘图方法中使用“CGPoint locationOfTouch”作为参数 下面是我正在使用的代码块Ios 如何使用核心图形在触摸位置绘制圆形?,ios,xcode,touch,cgcontext,Ios,Xcode,Touch,Cgcontext,新来的程序员。我在尝试使用核心图形在触摸位置周围绘制笔划弧时遇到问题。我有画圆圈的方法工作得很好,当我点击屏幕时,我已经测试并正在注册触摸,但是当我尝试调用该方法在点击时画圆圈时,我得到错误“CGContextBlahBlah:invalid context 0x0” 我想这是因为我没有调用drawRect()中的方法 那么我怎样才能在触摸屏上调用这个方法呢?此外,如何在绘图方法中使用“CGPoint locationOfTouch”作为参数 下面是我正在使用的代码块 -(void)touche
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint locationOfTouch = [touch locationInView:self];
[self drawTouchCircle:(locationOfTouch)];
[self setNeedsDisplay];
}
-(void)drawTouchCircle:(CGPoint)locationOfTouch
{
CGContextRef ctx= UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
CGContextSetLineWidth(ctx,5);
CGContextSetRGBStrokeColor(ctx,0.8,0.8,0.8,1.0);
CGContextAddArc(ctx,locationOfTouch.x,locationOfTouch.y,30,0.0,M_PI*2,YES);
CGContextStrokePath(ctx);
}
提前感谢您的帮助 是的,你说得对。问题是,与其自己调用
drawTouchCircle
,不如实现一个drawRect
方法来为您调用它,因此您的Touchs
方法只需要调用setNeedsDisplay
,剩下的部分由drawRect
来处理。因此,您可能希望在类属性中保存触摸位置,然后在drawRect
中检索该位置:
@interface View ()
@property (nonatomic) BOOL touched;
@property (nonatomic) CGPoint locationOfTouch;
@end
@implementation View
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesBegan:touches withEvent:event];
self.touched = YES;
UITouch *touch = [touches anyObject];
self.locationOfTouch = [touch locationInView:self];
[self setNeedsDisplay];
}
- (void)drawTouchCircle:(CGPoint)locationOfTouch
{
CGContextRef ctx= UIGraphicsGetCurrentContext();
CGRect bounds = [self bounds];
CGPoint center;
center.x = bounds.origin.x + bounds.size.width / 2.0;
center.y = bounds.origin.y + bounds.size.height / 2.0;
CGContextSaveGState(ctx);
CGContextSetLineWidth(ctx,5);
CGContextSetRGBStrokeColor(ctx,0.8,0.8,0.8,1.0);
CGContextAddArc(ctx,locationOfTouch.x,locationOfTouch.y,30,0.0,M_PI*2,YES);
CGContextStrokePath(ctx);
}
- (void)drawRect:(CGRect)rect
{
if (self.touched)
[self drawTouchCircle:self.locationOfTouch];
}
@end
正如Rob所说,你的怀疑是正确的-在iOS中,所有的绘图都是拉而不是推。谢谢你的快速回答!这对我来说似乎是朝着正确的方向发展,所以谢谢你。在头文件中添加属性部分并在m文件中合成时,我收到一条警告,指出“locationOfTouch”的“LocalDeclaration”“隐藏实例变量。这是否意味着我需要使用合成以外的其他声明?抱歉,如果答案很明显,我仍在努力领会要点。@BendE作为旁白,您还说您已将此属性添加到.h文件中。新兴的最佳实践是不在.h文件中声明这些私有属性,而是在.m文件中的“私有类扩展名”中定义它,就像我上面所做的那样。这样,您就不会将其他类公开给属于
UIView
子类的私有实现细节的属性。现在,如果您需要其他类来访问它,那么一定要在.h文件中定义它。但如果没有,请将其保留在那里,并将其放在.m的私有类扩展中。嗯,似乎我的问题在于draw方法,因为我使用了locationOfTouch.x
而不是self.locationOfTouch.x
作为参数。虽然我触摸的时候还是什么都没有得到。另外,当我删除@synthetic
时,我会收到另一条警告,说明touch需要定义方法settouch谢谢您的回复!它现在似乎工作正常。