2012-07-04 28 views
13

tôi có mã:CGPoint để NSValue và đảo ngược

NSMutableArray *vertices = [[NSMutableArray alloc] init]; 

//Getting mouse coordinates 
loc = [self convertPoint: [event locationInWindow] fromView:self]; 
[vertices addObject:loc]; // Adding coordinates to NSMutableArray 

//Converting from NSMutableArray to GLfloat to work with OpenGL 
int count = [vertices count] * 2; // * 2 for the two coordinates of a loc object 
GLFloat []glVertices = (GLFloat *)malloc(count * sizeof(GLFloat)); 
int currIndex = 0; 
for (YourLocObject *loc in vertices) { 
    glVertices[currIndex++] = loc.x; 
    glVertices[currIndex++] = loc.y;   
} 

loc là CGPoint, vì vậy tôi cần phải bằng cách nào đó để thay đổi từ CGPoint để NSValue để thêm nó vào NSMutableArray và sau đó chuyển đổi nó trở lại CGPoint. Làm thế nào nó có thể được thực hiện?

Trả lời

20

Lớp NSValue có phương pháp +[valueWithPoint:]-[CGPointValue]? Đây có phải là những gì bạn đang tìm kiếm?

//Getting mouse coordinates 
NSMutableArray *vertices = [[NSMutableArray alloc] init]; 
CGPoint location = [self convertPoint:event.locationInWindow fromView:self]; 
NSValue *locationValue = [NSValue valueWithPoint:location]; 
[vertices addObject:locationValue]; 

//Converting from NSMutableArray to GLFloat to work with OpenGL 
NSUInteger count = vertices.count * 2; // * 2 for the two coordinates 
GLFloat GLVertices[] = (GLFloat *)malloc(count * sizeof(GLFloat)); 
for (NSUInteger i = 0; i < count; i++) { 
    NSValue *locationValue = [vertices objectAtIndex:i]; 
    CGPoint location = locationValue.CGPointValue; 
    GLVertices[i] = location.x; 
    GLVertices[i] = location.y; 
} 
+0

Tôi đã thử 'NSValue * cgpointObj = [Giá trị NSValueWithPoint: loc];'. Nhưng làm thế nào để chuyển đổi trở lại CGPoint? – hockeyman

+1

Một cái gì đó như 'CGPoint loc = cgpointObj.pointValue' sẽ hoạt động. Tôi đã thêm mã cập nhật. – Stream

+0

Tôi nghĩ rằng nó không thêm bất kỳ giá trị nào. Nếu tôi viết mã: | 'NSUInteger sum = vertices.count; NSLog (@ "count:% lu", sum); ' Nó luôn viết rằng tổng = 0. Tại sao? Không có giá trị nào được thêm vào? Vậy tại sao họ không được thêm vào? – hockeyman