2014-09-12 1 views
1

Я хочу рисовать линию с помощью UIPinchGeustureRecognizer, я пробовал все решения stackoverflow, но не повезло. пожалуйста, помогите мне решить это. Я получаю следующую ошибку:Draw Line Использование UIPinchGeustureRecognizer

Сначала я хочу знать, что моя логика кода верна или нет. И я не получил очки от touchbegan/touchmoved. Я получаю две точки от (void) handleLinePinch: (UIPinchGestureRecognizer *) жест.

//My instances in .h file 

CGPoint location1,location2; 
LineView* l; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    l = [[LineView alloc]initWithFrame:self.view.frame]; 
    [self.view addSubview:l]; 
    UIPinchGestureRecognizer *linepinch = [[UIPinchGestureRecognizer alloc]  
    initWithTarget:l action:@selector(handleLinePinch:)]; 
    [l addGestureRecognizer:linepinch]; 
} 


- (void)handleLinePinch:(UIPinchGestureRecognizer *)gesture 
{ 
    NSUInteger num_touches = [gesture numberOfTouches]; 

    // save locations to some instance variables, like `CGPoint location1, location2;` 
    if (num_touches >= 1) { 
     location1 = [gesture locationOfTouch:0 inView:l]; 
    } 
    if (num_touches >= 2) { 
     location2 = [gesture locationOfTouch:1 inView:l]; 
    } 
    [l drawRect:location1 Loc2:location2]; 
    [l setNeedsDisplay]; 

} 
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
} 
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 
} 
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 
} 


LineView.m 

- (void)drawRect:(CGPoint)location1 Loc2:(CGPoint)location2 { 

CGContextRef context = UIGraphicsGetCurrentContext(); 
CGContextSetLineWidth(context, 5.0); 
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB(); 
CGFloat components[] = {0.0, 0.0, 1.0, 1.0}; 
CGColorRef color = CGColorCreate(colorspace, components); 
CGContextSetStrokeColorWithColor(context, color); 
CGContextMoveToPoint(context, location1.x, location1.y); 
CGContextAddLineToPoint(context, location2.x, location2.y); 
CGContextStrokePath(context); 
CGColorSpaceRelease(colorspace); 
CGColorRelease(color); 
} 

ответ

2

Вы должны наследоваться UIView и переопределить метод drawRect:, то CGContextRef вы получаете с UIGraphicsGetCurrentContext недействительно из drawRect: метода и не создает сильную ссылку на графическом контекст, поскольку он может изменить между вызовами drawRect: способ.

Когда вы узнаете жест щепотки, передайте CGPoint на вид и отправьте метод setNeedsDisplay.

Всегда используйте setNeedsDisplay, чтобы обновить представление, не отправляйте напрямую drawRect:.

LineView.m

- (void)drawRect:(CGRect)rect 
{ 
    // p1 and p2 should be set before call `setNeedsDisplay` method 
    [self drawRect:location1 Loc2:location2] ; 
} 

- (void)drawRect:(CGPoint)location1 Loc2:(CGPoint)location2 { 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetLineWidth(context, 5.0); 
    CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB(); 
    CGFloat components[] = {0.0, 0.0, 1.0, 1.0}; 
    CGColorRef color = CGColorCreate(colorspace, components); 
    CGContextSetStrokeColorWithColor(context, color); 
    CGContextMoveToPoint(context, location1.x, location1.y); 
    CGContextAddLineToPoint(context, location2.x, location2.y); 
    CGContextStrokePath(context); 
    CGColorSpaceRelease(colorspace); 
    CGColorRelease(color); 
} 

Edit: Я предполагаю, что вы только нарисовать линию, когда два пальца находятся на.

- (void)handleLinePinch:(UIPinchGestureRecognizer *)gesture 
{ 
    NSUInteger num_touches = [gesture numberOfTouches]; 

    // save locations to some instance variables, like `CGPoint location1, location2;` 
    if (num_touches == 2) { 
     location1 = [gesture locationOfTouch:0 inView:l]; 
     location2 = [gesture locationOfTouch:1 inView:l]; 
    } 
    // you need save location1 and location2 to `l` and refresh `l`. 
    // for example: l.location1 = location1; l.location2 = location2; 
    [l setNeedsDisplay]; 

} 
+0

С какого места shoud я читал обновленные данные location1 и location2? Я имею в виду от touchsBegan/Moved или от (void) handleLinePinch? – user3714144

+0

@ user3714144 из 'handleLinePinch:'. – KudoCC

+0

Я сделал и работаю хорошо. Дело в том, как обнаружить нарисованную линию, чтобы перетащить линию. – user3714144

 Смежные вопросы

  • Нет связанных вопросов^_^