Skip to content

Instantly share code, notes, and snippets.

@taylorhughes
Created August 26, 2014 00:30
Show Gist options
  • Save taylorhughes/485f02af6a9d52472ac3 to your computer and use it in GitHub Desktop.
Save taylorhughes/485f02af6a9d52472ac3 to your computer and use it in GitHub Desktop.
//
// ImgixURL.h
// Cluster
//
// Created by Taylor Hughes on 12/18/12.
// Copyright (c) 2012 Taylor Hughes. All rights reserved.
//
#import "NSDictionary+FormEncoded.h"
typedef enum {
ImgixFitClip,
ImgixFitCrop,
ImgixFitScale,
ImgixFitFill,
ImgixFitMax,
} ImgixFit;
@interface ImgixURL : NSObject
- initWithS3URL:(NSURL*)URL s3Bucket:(NSString*)bucketName imgixDomain:(NSString*)domain;
- (NSURL*) urlWithWidth:(NSUInteger)width height:(NSUInteger)height;
- (NSURL*) urlWithWidth:(NSUInteger)width height:(NSUInteger)height fit:(ImgixFit)fit;
@end
//
// ImgixURL.m
// Cluster
//
// Created by Taylor Hughes on 12/18/12.
// Copyright (c) 2012 Taylor Hughes. All rights reserved.
//
#import "ImgixURL.h"
NSString *ImgixFitToUrlParam(ImgixFit fit) {
switch (fit) {
case ImgixFitClip:
return @"clip";
case ImgixFitCrop:
return @"crop";
case ImgixFitFill:
return @"fill";
case ImgixFitMax:
return @"max";
case ImgixFitScale:
return @"scale";
}
return nil;
}
@interface ImgixURL ()
@property (strong, nonatomic) NSString *baseURL;
@property (assign, nonatomic) NSString *joinChar;
@end
@implementation ImgixURL
- initWithS3URL:(NSURL*)URL s3Bucket:(NSString*)bucketName imgixDomain:(NSString*)domain
{
self = [super init];
if (self) {
NSString *bucketHost = [NSString stringWithFormat:@"%@.s3.amazonaws.com", bucketName];
NSString *baseURL = [[URL absoluteString] stringByReplacingOccurrencesOfString:bucketHost withString:domain];
NSString *bucketPath = [NSString stringWithFormat:@"//s3.amazonaws.com/%@/", bucketName];
NSString *imgixPath = [NSString stringWithFormat:@"//%@/", domain];
self.baseURL = [baseURL stringByReplacingOccurrencesOfString:bucketPath withString:imgixPath];
// TODO(taylor): Actually parse the URL.
if ([self.baseURL rangeOfString:@"?"].location != NSNotFound) {
self.joinChar = @"&";
} else {
self.joinChar = @"?";
}
}
return self;
}
- (NSURL*) urlWithWidth:(NSUInteger)width height:(NSUInteger)height
{
return [self urlWithWidth:width height:height fit:ImgixFitCrop];
}
- (NSURL*) urlWithWidth:(NSUInteger)width height:(NSUInteger)height fit:(ImgixFit)fit
{
// Figure out the device-pixel ratio.
CGFloat devicePixelRatio = [[UIScreen mainScreen] scale];
NSDictionary *params = @{
@"w": [NSString stringWithFormat:@"%d", width],
@"h": [NSString stringWithFormat:@"%d", height],
@"fit": ImgixFitToUrlParam(fit),
@"dpr": [NSString stringWithFormat:@"%0.2f", devicePixelRatio],
};
NSURL *url = [NSURL URLWithString:[self.baseURL stringByAppendingFormat:@"%@%@", self.joinChar, [params toFormEncodedString]]];
return url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment