Search code examples
iosuiimagensarraycgsize

how to get CGSizes of image urls in NSArray


I have a NSArray which contains NSStrings of image urls like so:

NSArray *array = [NSArray arrayWithObjects:@"http://graphics8.nytimes.com/images/2014/07/22/blogs/20140722-lens-mark-slide-SG5C/20140722-lens-mark-slide-SG5C-custom1.jpg", @"http://graphics8.nytimes.com/images/2014/07/22/blogs/20140722-lens-mark-slide-SG5C/20140722-lens-mark-slide-SG5C-custom2.jpg", @"http://graphics8.nytimes.com/images/2014/07/22/blogs/20140722-lens-mark-slide-6N62/20140722-lens-mark-slide-6N62-blog480.jpg", nil];

How do I get the CGSize of each imageUrl?

I know how to get the size of one imageUrl like so:

UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://graphics8.nytimes.com/images/2014/07/22/blogs/20140722-lens-mark-slide-SG5C/20140722-lens-mark-slide-SG5C-jumbo.jpg"]]];
CGSize imageSize = image.size;

Solution

  • for(NSString *stringURL in array)
    {
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:stringURL]]];
        CGSize imageSize = image.size;
    }
    

    I would not suggest doing it in main thread.

    If you want to get array of sizes you should do the following:

    NSMutableArray *sizes = [NSMutableArray array];
    for(NSString *stringURL in array)
    {
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:stringURL]]];
        CGSize imageSize = image.size;
        [sizes addObject:[NSValue valueWithCGSize:imageSize];
    }
    

    After that you can get CGSize in the following way:

    CGSize imageSize = [sizes[index] CGSizeValue];