2012-10-28 3 views
1

한 개체와 사용자가 만난 곳 사이에 선을 그리려합니다. 서브 클래 싱을 시도했는데 사용자가 화면에 닿을 때마다 "- (void) drawrect"를 업데이트 할 수 없습니다. 나는 그 파일을 삭제하고 오른쪽에 코드를 퍼팅 시도 "- (무효) touchesbegan"하지만, 그것은 작동하지 않습니다 필요한 경우사용자가 터치 한 위치에 선을 그리려면 어떻게해야합니까?

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 

    UITouch *touch = [touches anyObject]; 
    CGPoint locationOfTouch = [touch locationInView:nil]; 
    // You can now use locationOfTouch.x and locationOfTouch.y as the user's coordinates 



Int xpos = (int)(starShip.center.x); 
int ypos = (int)(starShip.center.y); 

    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0); 
     CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0); 
    CGContextBeginPath(UIGraphicsGetCurrentContext()); 
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), starShip.center.x, starShip.center.y); 
    //draws a line to the point where the user has touched the screen 
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), locationOfTouch.x, locationOfTouch.y); 
    CGContextStrokePath(UIGraphicsGetCurrentContext()); 
} 

답변

0

drawRect: 만이라고합니다. 뷰가 처음 표시 될 때마다 그리고 뷰의 크기가 변경 될 때마다 자동으로 호출됩니다. 접촉 후 전화를 받으려면 [self setNeedsDisplay];으로 전화해야합니다.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    [self setNeedsDisplay]; 
} 

이렇게하면 drawRect: 메서드가 호출됩니다. drawRect:을 직접 호출하지 마십시오. 한 프레임에서 여러 번 호출했기 때문에 뷰가 여러 번 다시 그려집니다. 대신 setNeedsDisplay을 사용하여 다시 그리기가 필요하다고 플래그를 지정합니다. 이 방법으로 drawRect:은 한 번만 호출되며 아무리 자주 setNeedsDisplay으로 전화를 걸어도됩니다.

+0

감사합니다. 하지만 하위 클래스 또는보기 컨트롤러 drawrect 넣을 수 있습니까? – CompleteXcodeNoob

+0

'drawRect :'는'UIViewController'가 아닌'UIView'의 메소드입니다. – DrummerB

+0

감사합니다. – CompleteXcodeNoob

관련 문제