CGPoint到NSValue并反转

时间:2012-07-04 10:27:32

标签: objective-c xcode macos cocoa

我有代码:

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是CGPoint,所以我需要以某种方式从CGPoint更改为NSValue以将其添加到NSMutableArray,之后将其转换回CGPoint。怎么可能呢?

1 个答案:

答案 0 :(得分:21)

班级NSValue有方法+[valueWithPoint:]-[CGPointValue]?这是你在找什么?

//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;
}