iOS 开发常用的50个工具方法

1、获取毫秒级时间戳
+ (NSString *)getTimeLocal{//毫秒级
    UInt64 recordTime = [[NSDate date] timeIntervalSince1970]*1000;
    NSString *timeLocal = [[NSString alloc] initWithFormat:@"%llu", recordTime];
    return timeLocal;
}
2、获取秒级时间戳
+ (NSString *)getTimeLocalSEC{//秒级
    UInt64 recordTime = [[NSDate date] timeIntervalSince1970];
    NSString *timeLocal = [[NSString alloc] initWithFormat:@"%llu", recordTime];
    return timeLocal;
}
3、获取ipv6地址
+ (NSDictionary *> *)getAllIPV6 {
    struct ifaddrs *interfaceList = nil;
    if (getifaddrs(&interfaceList) != 0 || interfaceList == nil) {
        return nil;
    }
    NSSet *interfaceWhiteList = [NSSet setWithObjects:@"en0", @"pdp_ip0", @"pdp_ip1", nil];
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    struct ifaddrs *interface = interfaceList;
    char addrBuf[INET6_ADDRSTRLEN];
    do {
        if (!(interface->ifa_flags & IFF_UP)) {
            continue;
        }
        NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
        if (![interfaceWhiteList containsObject:name]) {
            continue;
        }
        const struct sockaddr_in6 *addr = (const struct sockaddr_in6 *)interface->ifa_addr;
        if (!addr || addr->sin6_family != AF_INET6) {
            continue;
        }
        if (inet_ntop(AF_INET6, &addr->sin6_addr, addrBuf, INET6_ADDRSTRLEN) && strncmp("fe80::", addrBuf, 6) != 0) {
            NSMutableArray *ipList = [result objectForKey:name]; if (ipList == nil) {
            ipList = [NSMutableArray array]; [result setObject:ipList forKey:name];
            }
            [ipList addObject:[NSString stringWithUTF8String:addrBuf]];
        }
    } while((interface = interface->ifa_next));
    freeifaddrs(interfaceList);
    return result;
}
4、获取设备型号
+ (NSString *)getModel{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
    return platform?:@"";
}
5、获取总内存空间
+ (NSString *)getTotalMemory{
    int64_t totalMemory = [[NSProcessInfo processInfo] physicalMemory];
    if (totalMemory < -1) totalMemory = -1;
    NSString *totalMemoryStr = [NSString stringWithFormat:@"%lld",totalMemory];
    return totalMemoryStr?:@"-1";
}
6、获取磁盘总空间
+ (NSString *)getTotalDiskSpace{
    NSError *error = nil;
    NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
    if (error) return @"-1";
    int64_t space =  [[attrs objectForKey:NSFileSystemSize] longLongValue];
    if (space < 0) space = -1;
    NSString *totalMemoryStr = [NSString stringWithFormat:@"%lld",space];
    return totalMemoryStr?:@"-1";
}
7、获取IDFA
+(NSString *)getIDFA{
    NSString *idfa = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    return idfa ?: @"";
}
8、获取IDFV
+(NSString *)getIDFV{
    NSUUID *UUID = [[UIDevice currentDevice] identifierForVendor];
    NSString *idfv = [NSString stringWithFormat:@"%@",UUID.UUIDString];
    return idfv;
}
9、获取IMSI
+ (NSString *)getIMSI{
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = [info subscriberCellularProvider];
    NSString *mcc = [carrier mobileCountryCode];
    NSString *mnc = [carrier mobileNetworkCode];
    NSString *imsi = [NSString stringWithFormat:@"%@%@", mcc, mnc];
    return imsi?imsi:@"";
}
10、获取硬件型号
static NSString *sf_HWModel()
{
    size_t size;
    sysctlbyname("hw.model", NULL, &size, NULL, 0);
    char *model = malloc(size);
    sysctlbyname("hw.model", model, &size, NULL, 0);
    NSString *result = [NSString stringWithUTF8String:model];
    free(model);
    return result ?: @"";
}
11、获取系统型号
static NSString *sf_HWMachine()
{
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *result = [NSString stringWithUTF8String:machine];
    free(machine);
    return result ?: @"";
}
12、判断手机是否越狱
+ (BOOL)isJailbroken{
    BOOL jailbroken = NO;
    NSString *cydiaPath = @"/Applications/Cydia.app";
    NSString *aptPath = @"/private/var/lib/apt/";
    if ([[NSFileManager defaultManager] fileExistsAtPath:cydiaPath]) {
        jailbroken = YES;
    }
    if ([[NSFileManager defaultManager] fileExistsAtPath:aptPath]) {
        jailbroken = YES;
    }
    return jailbroken;
}
13、获取系统版本
+ (NSString *)getOS
{
    NSString *os = [[UIDevice currentDevice] systemVersion];
    return [NSString stringWithFormat:@"%@",os];
}
14、设备类型及屏幕方向
//设备屏幕方向
[[UIDevice currentDevice] orientation];
//设备类型
[[UIDevice currentDevice] userInterfaceIdiom]
15、获取应用包名
+ (NSString *)getPackageName
{
    NSString *packageName = [NSString stringWithFormat:@"%@",[[NSBundle mainBundle] bundleIdentifier]];
    return packageName;
}
16、获取设备语言
+ (NSString *)getLanguage{
    NSArray *allLanguages = [[NSUserDefaults standardUserDefaults] arrayForKey:@"AppleLanguages"];
    if ([allLanguages firstObject] && [[allLanguages firstObject] isKindOfClass:[NSString class]]) {
        NSString *preferredLang = [allLanguages firstObject];
        return preferredLang?preferredLang:@"zh-Hans-CN";
    }
    return @"zh-Hans-CN";
}
17、获取设备国家
+ (NSString *)getCountry{
    NSLocale *locale = [NSLocale currentLocale];
    NSString *displayNameString = [locale objectForKey:NSLocaleCountryCode];
    return displayNameString?:@"CN";
}
18、获取应用名称
+ (NSString *)getAppName{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app名称
    NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    return app_Name?app_Name:@"";
}
19、获取应用版本
+ (NSString *)getAppVersion{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // App Version
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return app_Version?app_Version:@"";
}
20、获取应用Build
+ (NSString *)getAppBuild{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // App Build
    NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
    return app_build?app_build:@"";
}
21、获取设备激活时间
static NSString *sf_getFileTime() {
    struct stat info;
    int result = stat("/var/mobile", &info);
    if (result != 0) {
        return @"";
    }
    struct timespec time = info.st_birthtimespec;
    return [NSString stringWithFormat:@"%ld.%09ld", time.tv_sec, time.tv_nsec];
}
22、获取update_time
+ (NSString *)getUpdateTime
{
    NSString *timeString = nil;
    struct stat sb;
    NSString *enCodePath = @"L3Zhci9tb2JpbGU=";
    NSData *data=[[NSData alloc]initWithBase64EncodedString:enCodePath options:0];
    NSString *dataString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    const char* dePath = [dataString cStringUsingEncoding:NSUTF8StringEncoding];
    if (stat(dePath, &sb) != -1) {
        timeString = [NSString stringWithFormat:@"%d.%d", (int)sb.st_ctimespec.tv_sec, (int)sb.st_ctimespec.tv_nsec];
    }
    else {
        timeString = @"0.0";
    }
    return timeString?:@"";
}
23、获取boot_time
+ (NSString *)getBootTime{
    NSString *timeString = nil;
    struct timeval boottime;
    int mib[2] = {CTL_KERN, KERN_BOOTTIME};
    size_t size = sizeof(boottime);

    if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 && boottime.tv_sec != 0)
    {
        timeString = [NSString stringWithFormat:@"%@", [NSNumber numberWithLong:boottime.tv_sec]];
    }
    return timeString?:@"";
}
24、获取APP更新时间
+ (NSString *)getAppUpdateTime {
    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"Info" ofType:@"plist"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:bundlePath error:nil];
    NSDate *date = [fileAttributes objectForKey:NSFileCreationDate];
    NSString *timeString = [NSString stringWithFormat:@"%@", [NSNumber numberWithDouble:date.timeIntervalSince1970]];
    return timeString?:@"";
}
25、获取本机运营商名称
+ (NSInteger)getYunYingShang{
    //获取本机运营商名称
    CTCarrier *carrier = [[SFNetTool defaultManager].info subscriberCellularProvider];
    //当前手机所属运营商名称
    NSString *mobile;
    //先判断有没有SIM卡,如果没有则不获取本机运营商
    if (!carrier.isoCountryCode) {
//        NSLog(@"没有SIM卡");
        mobile = @"无运营商";
    }else{
        mobile = [carrier carrierName];
    }
    return mobile;
}
26、获取设备安全区域
+ (UIEdgeInsets)getWindowSafeAreaInsets{
    if (@available(iOS 11.0, *)) {
        UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];
        return mainWindow.safeAreaInsets;
    }
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
27、获取设备时区
+ (NSString *)getNowTimezone{
    [NSTimeZone resetSystemTimeZone]; // 重置手机系统的时区
    NSInteger offset = [NSTimeZone localTimeZone].secondsFromGMT;//获取距离0时区偏差的时间
    offset = offset/3600; // +8 东八区, -8 西八区
    NSString *tzStr = [NSString stringWithFormat:@"%ld", (long)offset];
    return tzStr?:@"";
}
28、判断View是否显示在屏幕上
+ (BOOL)isInScreenView:(UIView*)view
{
    if (view == nil) {
        return false;
    }
    CGRect screenRect = [UIScreen mainScreen].bounds;
    // 转换view对应window的Rect
    CGRect rect = [view convertRect:view.frame fromView:nil];
    if (CGRectIsEmpty(rect) || CGRectIsNull(rect)) {
        return false;
    }
    // 若view 隐藏
    if (view.hidden) {
        return false;
    }
    // 若没有superview
    if (view.superview == nil) {
        return false;
    }
    // 若size为CGrectZero
    if (CGSizeEqualToSize(rect.size, CGSizeZero)) {
        return false;
    }
    // 获取 该view与window 交叉的 Rect
    CGRect intersectionRect = CGRectIntersection(rect, screenRect);
    if (CGRectIsEmpty(intersectionRect) || CGRectIsNull(intersectionRect)) {
        return false;
    }
    return true;
}
29、json字符串转字典
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err) {
        return nil;
    }
    return dic;
}

30、提取URL链接的所有参数

+ (NSMutableDictionary *)parseURLParametersWithURLStr:(NSString *)urlStr {
    if (!urlStr) {
        return nil;
    }
    NSRange range = [urlStr rangeOfString:@"?"];
    if (range.location == NSNotFound) return nil;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    NSString *parametersString = [urlStr substringFromIndex:range.location + 1];
    if ([parametersString containsString:@"&"]) {
        NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
        for (NSString *keyValuePair in urlComponents) {
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
            NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
            if (key == nil || value == nil) {
                continue;
            }
            id existValue = [parameters valueForKey:key];
            if (existValue != nil) {
                if ([existValue isKindOfClass:[NSArray class]]) {
                    NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
                    [items addObject:value];
                    [parameters setValue:items forKey:key];
                } else {
                    [parameters setValue:@[existValue, value] forKey:key];
                }
            } else {
                [parameters setValue:value forKey:key];
            }
        }
    } else {
        NSArray *pairComponents = [parametersString componentsSeparatedByString:@"="];
        if (pairComponents.count == 1) {
            return nil;
        }
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
        if (key == nil || value == nil) {
            return nil;
        }
        [parameters setValue:value forKey:key];
    }
    
    return parameters;
}

31、提取字符串中的数字

+ (NSString *)getNumberFromDataStr:(NSString *)str{
    NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    return[[str componentsSeparatedByCharactersInSet:nonDigitCharacterSet] componentsJoinedByString:@""];
}

32、添加抖动动画

+ (void)addImageRotationWithView:(UIView *)view Count:(float)count{
    CAKeyframeAnimation *anima = [CAKeyframeAnimation animation];
    anima.keyPath = @"transform.rotation";
    anima.values = @[@(((-5) * M_PI / 180.0)),@(((5) * M_PI / 180.0)),@(((-5) * M_PI / 180.0))];
    anima.repeatCount = count;
    [view.layer addAnimation:anima forKey:@"doudong"];
}

33、添加缩放动画

+ (void)addImageScaleWithView:(UIView *)view repeatCount:(float)count{
    CAKeyframeAnimation *anima = [CAKeyframeAnimation animation];
    anima.keyPath = @"transform.scale";
    anima.values = @[@(1.0),@(1.2),@(1.0),@(0.8),@(1.0)];
    anima.repeatCount = count;
    anima.duration = 1;
    [view.layer addAnimation:anima forKey:@"suofang"];
}

34、添加阴影

+ (void)addShadowToView:(UIView *)theView withColor:(UIColor *)theColor shadowRadius:(CGFloat)radius{
    // 阴影颜色
    theView.layer.shadowColor = theColor.CGColor;
    // 阴影偏移,默认(0, -3)
    theView.layer.shadowOffset = CGSizeMake(0,0);
    // 阴影透明度,默认0
    theView.layer.shadowOpacity = 0.5;
    // 阴影半径,默认3
    theView.layer.shadowRadius = radius;
}

35、添加渐变色

+ (void)addGradientLayerWithUIColors:(NSArray*)colors View:(UIView*)view {
    NSMutableArray *colorArray = [NSMutableArray array];
    for (UIColor *color in colors) {
        [colorArray addObject:(id)color.CGColor];
    }
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = view.bounds;
    gradient.startPoint = CGPointMake(0, 0);
    gradient.endPoint = CGPointMake(1, 0);
    gradient.colors = colorArray;
    for (CAGradientLayer *oldGLayer in view.layer.sublayers) {
        [oldGLayer removeFromSuperlayer];
    }
    [view.layer addSublayer:gradient];
}

36、获取当前window、顶层控制器

+ (UIWindow *)getKeyWindow{
    UIWindow* window = nil;
    if (@available(iOS 13.0, *)) {
        for (UIWindowScene* windowScene in [UIApplication sharedApplication].connectedScenes) {
            if (windowScene.activationState == UISceneActivationStateForegroundActive) {
                window = windowScene.windows.firstObject;
                break;
            }
        }
    }else{
        window = [UIApplication sharedApplication].keyWindow;
    }
    return window;
}
+ (UIViewController *)topViewController {
    UIViewController *resultVC = [self topViewControllerWithVC:[self getKeyWindow].rootViewController];
    while (resultVC.presentedViewController) {
        resultVC = [self topViewControllerWithVC:resultVC.presentedViewController];
    }
    return resultVC;
}
+ (UIViewController *)topViewControllerWithVC:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self topViewControllerWithVC:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self topViewControllerWithVC:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}

37、减淡当前颜色

+ (UIColor *)shallowerWithColor:(UIColor *)color{
    CGFloat R,G,B;
    const CGFloat *components = CGColorGetComponents(color.CGColor);
    R = components[0];
    G = components[1];
    B = components[2];
    UIColor *newColor = [UIColor colorWithRed:R+0.1 green:G+0.1 blue:B+0.1 alpha:1.0];
    return newColor;
}

38、文字转图片

//文字转化成图片
+ (UIImage *)imageFromText:(NSString *)content FontSize:(CGFloat)fontSize TextColor:(UIColor *)textColor BgColor:(UIColor *)bgColor{
    UIFont *font = [UIFont systemFontOfSize:fontSize weight:UIFontWeightRegular];
    CGRect stringRect = [content boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil];
    CGRect rect = CGRectMake(10, 5, stringRect.size.width + 20, stringRect.size.height + 10);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, UIScreen.mainScreen.scale);
    if(bgColor) {
        //填充背景颜色
        [bgColor set];
        UIRectFill(CGRectMake(0, 0, rect.size.width, rect.size.height));
    }
    // 根据矩形画带圆角的曲线
    [content drawInRect:rect withAttributes:@{NSFontAttributeName:font, NSForegroundColorAttributeName:textColor}];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

39、获取正则匹配结果

+ (NSArray *)matchString:(NSString *)string toRegexString:(NSString *)regexStr{
    if (string.length>0) {
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionAnchorsMatchLines error:nil];
        NSArray * matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
        //match: 所有匹配到的字符,根据() 包含级
        NSMutableArray *array = [NSMutableArray array];
        for (NSTextCheckingResult *match in matches) {
            //以正则中的(),划分成不同的匹配部分
            NSString *component = [string substringWithRange:[match rangeAtIndex:1]];
            [array addObject:component];
        }
        return array;
    } else {
        return @[@""];
    }
}

40、字符串转颜色

+ (UIColor *)colorWithDarkModelColor:(NSString *)color{
    return [self colorWithDarkModelColor:color andOpacity:1.0f];
}
+ (UIColor *)colorWithDarkModelColor:(NSString *)color andOpacity:(CGFloat)opacity {
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    //判断前缀
    if ([cString hasPrefix:@"0X"]) {
        cString = [cString substringFromIndex:2];
    }
    if ([cString hasPrefix:@"0x"]) {
        cString = [cString substringFromIndex:2];
    }
    if ([cString hasPrefix:@"#"]) {
        cString = [cString substringFromIndex:1];
    }
    if ([cString length] != 6) {
        return [UIColor clearColor];
    }
    
    //从六位数值中找到RGB对应的位数并转换
    NSRange range;
    range.location = 0;
    range.length = 2;
    //R G B
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    if (@available(iOS 13.0, *)) {
        return [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle==UIUserInterfaceStyleDark) {
                return [UIColor colorWithRed:((float) (255.0-r) / 255.0f) green:((float) (255.0-g) / 255.0f) blue:((float) (255.0-b) / 255.0f) alpha:opacity];
            } else {
                return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:opacity];
            }
        }];
    } else {
        // Fallback on earlier versions
        return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:opacity];
    };
}

41、颜色转图片

+ (UIImage *)sf_imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

42、转灰度图

- (UIImage *)sf_convertToGrayImage {
    int width = self.size.width;
    int height = self.size.height;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate(nil,width,height,8,0,colorSpace,kCGImageAlphaNone);
    CGColorSpaceRelease(colorSpace);
    if (context == NULL) {
        return nil;
    }
    CGContextDrawImage(context,CGRectMake(0, 0, width, height), self.CGImage);
    CGImageRef contextRef = CGBitmapContextCreateImage(context);
    UIImage* grayImage = [UIImage imageWithCGImage:contextRef];
    CGContextRelease(context);
    CGImageRelease(contextRef);
    return grayImage;
}

43、图片翻转

/*
    UIImageOrientationUp,            // default orientation
    UIImageOrientationDown,          // 180 deg rotation
    UIImageOrientationLeft,          // 90 deg CCW
    UIImageOrientationRight,         // 90 deg CW
    UIImageOrientationUpMirrored,    // as above but image mirrored along other axis. horizontal flip
    UIImageOrientationDownMirrored,  // horizontal flip
    UIImageOrientationLeftMirrored,  // vertical flip
    UIImageOrientationRightMirrored, // vertical flip
*/
- (UIImage *)sf_fixOrientation {
    if (self.imageOrientation == UIImageOrientationUp) return self;
    CGAffineTransform transform = CGAffineTransformIdentity;
    switch (self.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, self.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationUpMirrored:
            break;
    }
    switch (self.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationDown:
        case UIImageOrientationLeft:
        case UIImageOrientationRight:
            break;
    }
    CGContextRef ctx = CGBitmapContextCreate(NULL, self.size.width, self.size.height,
                                             CGImageGetBitsPerComponent(self.CGImage), 0,
                                             CGImageGetColorSpace(self.CGImage),
                                             CGImageGetBitmapInfo(self.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (self.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.height,self.size.width), self.CGImage);
            break;
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.width,self.size.height), self.CGImage);
            break;
    }
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage* img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

- (UIImage *)sf_rotate:(UIImageOrientation)orient {
    CGRect bnds = CGRectZero;
    UIImage* copy = nil;
    CGContextRef ctxt = nil;
    CGImageRef imag = self.CGImage;
    CGRect rect = CGRectZero;
    CGAffineTransform tran = CGAffineTransformIdentity;
    rect.size.width = CGImageGetWidth(imag);
    rect.size.height = CGImageGetHeight(imag);
    bnds = rect;
    switch (orient) {
        case UIImageOrientationUp:
            return self;
        case UIImageOrientationUpMirrored:
            tran = CGAffineTransformMakeTranslation(rect.size.width, 0.0);
            tran = CGAffineTransformScale(tran, -1.0, 1.0);
            break;
            
        case UIImageOrientationDown:
            tran = CGAffineTransformMakeTranslation(rect.size.width,
                                                    rect.size.height);
            tran = CGAffineTransformRotate(tran, M_PI);
            break;
            
        case UIImageOrientationDownMirrored:
            tran = CGAffineTransformMakeTranslation(0.0, rect.size.height);
            tran = CGAffineTransformScale(tran, 1.0, -1.0);
            break;
            
        case UIImageOrientationLeft:
            bnds = sf_swapWidthAndHeight(bnds);
            tran = CGAffineTransformMakeTranslation(0.0, rect.size.width);
            tran = CGAffineTransformRotate(tran, 3.0 * M_PI / 2.0);
            break;
            
        case UIImageOrientationLeftMirrored:
            bnds = sf_swapWidthAndHeight(bnds);
            tran = CGAffineTransformMakeTranslation(rect.size.height,
                                                    rect.size.width);
            tran = CGAffineTransformScale(tran, -1.0, 1.0);
            tran = CGAffineTransformRotate(tran, 3.0 * M_PI / 2.0);
            break;
            
        case UIImageOrientationRight:
            bnds = sf_swapWidthAndHeight(bnds);
            tran = CGAffineTransformMakeTranslation(rect.size.height, 0.0);
            tran = CGAffineTransformRotate(tran, M_PI / 2.0);
            break;
            
        case UIImageOrientationRightMirrored:
            bnds = sf_swapWidthAndHeight(bnds);
            tran = CGAffineTransformMakeScale(-1.0, 1.0);
            tran = CGAffineTransformRotate(tran, M_PI / 2.0);
            break;
            
        default:
            return self;
    }
    
    UIGraphicsBeginImageContext(bnds.size);
    ctxt = UIGraphicsGetCurrentContext();
    switch (orient) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            CGContextScaleCTM(ctxt, -1.0, 1.0);
            CGContextTranslateCTM(ctxt, -rect.size.height, 0.0);
            break;
            
        default:
            CGContextScaleCTM(ctxt, 1.0, -1.0);
            CGContextTranslateCTM(ctxt, 0.0, -rect.size.height);
            break;
    }
    CGContextConcatCTM(ctxt, tran);
    CGContextDrawImage(UIGraphicsGetCurrentContext(), rect, imag);
    copy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return copy;
}

44、将图片旋转degrees角度

- (UIImage *)sf_imageRotatedByRadians:(CGFloat)radians {
    UIView* rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.size.width, self.size.height)];
    CGAffineTransform t = CGAffineTransformMakeRotation(radians);
    rotatedViewBox.transform = t;
    CGSize rotatedSize = rotatedViewBox.frame.size;
    UIGraphicsBeginImageContext(rotatedSize);
    CGContextRef bitmap = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);
    CGContextRotateCTM(bitmap, radians);
    CGContextScaleCTM(bitmap, 1.0, -1.0);
    CGContextDrawImage(bitmap, CGRectMake(-self.size.width / 2, -self.size.height / 2, self.size.width, self.size.height), [self CGImage]);
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

45、截取当前image对象rect区域内的图像

- (UIImage *)sf_subImageWithRect:(CGRect)rect {
    CGImageRef newImageRef = CGImageCreateWithImageInRect(self.CGImage, rect);
    UIImage* newImage = [UIImage imageWithCGImage:newImageRef];
    CGImageRelease(newImageRef);
    return newImage;
}

46、压缩图片至指定尺寸

- (UIImage *)sf_rescaleImageToSize:(CGSize)size {
    CGRect rect = (CGRect){CGPointZero, size};
    UIGraphicsBeginImageContext(rect.size);
    [self drawInRect:rect];
    UIImage* resImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resImage;
}

47、压缩图片至指定像素

- (UIImage *)sf_rescaleImageToPX:(CGFloat )toPX {
    CGSize size = self.size;
    if(size.width <= toPX && size.height <= toPX) {
        return self;
    }
    CGFloat scale = size.width / size.height;
    if(size.width > size.height) {
        size.width = toPX;
        size.height = size.width / scale;
    } else {
        size.height = toPX;
        size.width = size.height * scale;
    }
    return [self sf_rescaleImageToSize:size];
}

48、UIView转化为UIImage

+ (UIImage *)sf_imageFromView:(UIView *)view {
    CGFloat scale = [UIScreen mainScreen].scale;
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

49、数字本地化显示

+ (NSString *)chinaStringWithInteger:(NSInteger)number{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = NSNumberFormatterSpellOutStyle;
    NSString *string = [formatter stringFromNumber:[NSNumber numberWithInteger:number]];
    return string;
}

50、获取指定路径下的所有文件以及文件夹

// APP 路径
NSString *path = [[NSBundle mainBundle] bundlePath]; 
// 沙盒路径
NSString *path = NSHomeDirectory();
-(void)localFileWithPath:(NSString *)path {
    NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:path];
    NSString *fileName;
    while (fileName = [dirEnum nextObject]) {
        NSLog(@"文件路径:%@", fileName);
    }
}

你可能感兴趣的:(iOS 开发常用的50个工具方法)