iOS 開發(fā)常用的50個(gè)工具方法

1勺馆、獲取毫秒級(jí)時(shí)間戳
+ (NSString *)getTimeLocal{//毫秒級(jí)
    UInt64 recordTime = [[NSDate date] timeIntervalSince1970]*1000;
    NSString *timeLocal = [[NSString alloc] initWithFormat:@"%llu", recordTime];
    return timeLocal;
}
2、獲取秒級(jí)時(shí)間戳
+ (NSString *)getTimeLocalSEC{//秒級(jí)
    UInt64 recordTime = [[NSDate date] timeIntervalSince1970];
    NSString *timeLocal = [[NSString alloc] initWithFormat:@"%llu", recordTime];
    return timeLocal;
}
3侨核、獲取ipv6地址
+ (NSDictionary<NSString *, NSArray<NSString *> *> *)getAllIPV6 {
    struct ifaddrs *interfaceList = nil;
    if (getifaddrs(&interfaceList) != 0 || interfaceList == nil) {
        return nil;
    }
    NSSet<NSString *> *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<NSString *> *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草穆、獲取設(shè)備型號(hào)
+ (NSString *)getModel{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
    return platform?:@"";
}
5、獲取總內(nèi)存空間
+ (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诗祸、獲取硬件型號(hào)
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、獲取系統(tǒng)型號(hào)
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轴总、判斷手機(jī)是否越獄
+ (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直颅、獲取系統(tǒng)版本
+ (NSString *)getOS
{
    NSString *os = [[UIDevice currentDevice] systemVersion];
    return [NSString stringWithFormat:@"%@",os];
}
14、設(shè)備類型及屏幕方向
//設(shè)備屏幕方向
[[UIDevice currentDevice] orientation];
//設(shè)備類型
[[UIDevice currentDevice] userInterfaceIdiom]
15怀樟、獲取應(yīng)用包名
+ (NSString *)getPackageName
{
    NSString *packageName = [NSString stringWithFormat:@"%@",[[NSBundle mainBundle] bundleIdentifier]];
    return packageName;
}
16功偿、獲取設(shè)備語言
+ (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、獲取設(shè)備國(guó)家
+ (NSString *)getCountry{
    NSLocale *locale = [NSLocale currentLocale];
    NSString *displayNameString = [locale objectForKey:NSLocaleCountryCode];
    return displayNameString?:@"CN";
}
18往堡、獲取應(yīng)用名稱
+ (NSString *)getAppName{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app名稱
    NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    return app_Name?app_Name:@"";
}
19械荷、獲取應(yīng)用版本
+ (NSString *)getAppVersion{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // App Version
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return app_Version?app_Version:@"";
}
20共耍、獲取應(yīng)用Build
+ (NSString *)getAppBuild{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // App Build
    NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
    return app_build?app_build:@"";
}
21、獲取設(shè)備激活時(shí)間
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更新時(shí)間
+ (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颤诀、獲取本機(jī)運(yùn)營(yíng)商名稱
+ (NSInteger)getYunYingShang{
    //獲取本機(jī)運(yùn)營(yíng)商名稱
    CTCarrier *carrier = [[SFNetTool defaultManager].info subscriberCellularProvider];
    //當(dāng)前手機(jī)所屬運(yùn)營(yíng)商名稱
    NSString *mobile;
    //先判斷有沒有SIM卡字旭,如果沒有則不獲取本機(jī)運(yùn)營(yíng)商
    if (!carrier.isoCountryCode) {
//        NSLog(@"沒有SIM卡");
        mobile = @"無運(yùn)營(yíng)商";
    }else{
        mobile = [carrier carrierName];
    }
    return mobile;
}
26、獲取設(shè)備安全區(qū)域
+ (UIEdgeInsets)getWindowSafeAreaInsets{
    if (@available(iOS 11.0, *)) {
        UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];
        return mainWindow.safeAreaInsets;
    }
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
27崖叫、獲取設(shè)備時(shí)區(qū)
+ (NSString *)getNowTimezone{
    [NSTimeZone resetSystemTimeZone]; // 重置手機(jī)系統(tǒng)的時(shí)區(qū)
    NSInteger offset = [NSTimeZone localTimeZone].secondsFromGMT;//獲取距離0時(shí)區(qū)偏差的時(shí)間
    offset = offset/3600; // +8 東八區(qū), -8 西八區(qū)
    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;
    // 轉(zhuǎn)換view對(duì)應(yīng)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字符串轉(zhuǎn)字典
+ (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鏈接的所有參數(shù)

+ (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屈暗、提取字符串中的數(shù)字

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

32、添加抖動(dòng)動(dòng)畫

+ (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剧包、添加縮放動(dòng)畫

+ (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;
    // 陰影偏移,默認(rèn)(0, -3)
    theView.layer.shadowOffset = CGSizeMake(0,0);
    // 陰影透明度疆液,默認(rèn)0
    theView.layer.shadowOpacity = 0.5;
    // 陰影半徑一铅,默認(rèn)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堕油、獲取當(dāng)前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、減淡當(dāng)前顏色

+ (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掉缺、文字轉(zhuǎn)圖片

//文字轉(zhuǎn)化成圖片
+ (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));
    }
    // 根據(jù)矩形畫帶圓角的曲線
    [content drawInRect:rect withAttributes:@{NSFontAttributeName:font, NSForegroundColorAttributeName:textColor}];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

39卜录、獲取正則匹配結(jié)果

+ (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: 所有匹配到的字符,根據(jù)() 包含級(jí)
        NSMutableArray *array = [NSMutableArray array];
        for (NSTextCheckingResult *match in matches) {
            //以正則中的(),劃分成不同的匹配部分
            NSString *component = [string substringWithRange:[match rangeAtIndex:1]];
            [array addObject:component];
        }
        return array;
    } else {
        return @[@""];
    }
}

40、字符串轉(zhuǎn)顏色

+ (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];
    }
    
    //從六位數(shù)值中找到RGB對(duì)應(yīng)的位數(shù)并轉(zhuǎn)換
    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眶明、顏色轉(zhuǎn)圖片

+ (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艰毒、轉(zhuǎn)灰度圖

- (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、圖片翻轉(zhuǎn)

/*
    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搜囱、將圖片旋轉(zhuǎn)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丑瞧、截取當(dāng)前image對(duì)象rect區(qū)域內(nèi)的圖像

- (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轉(zhuǎn)化為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、數(shù)字本地化顯示

+ (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);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末西乖,一起剝皮案震驚了整個(gè)濱河市澎怒,隨后出現(xiàn)的幾起案子添履,更是在濱河造成了極大的恐慌居砖,老刑警劉巖柬脸,帶你破解...
    沈念sama閱讀 216,997評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件念逞,死亡現(xiàn)場(chǎng)離奇詭異分扎,居然都是意外死亡罚攀,警方通過查閱死者的電腦和手機(jī)蛛枚,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來萝玷,“玉大人,你說我怎么就攤上這事昆婿∏虻铮” “怎么了?”我有些...
    開封第一講書人閱讀 163,359評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵仓蛆,是天一觀的道長(zhǎng)睁冬。 經(jīng)常有香客問我,道長(zhǎng)看疙,這世上最難降的妖魔是什么豆拨? 我笑而不...
    開封第一講書人閱讀 58,309評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮能庆,結(jié)果婚禮上施禾,老公的妹妹穿的比我還像新娘。我一直安慰自己搁胆,他們只是感情好弥搞,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,346評(píng)論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著渠旁,像睡著了一般攀例。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上顾腊,一...
    開封第一講書人閱讀 51,258評(píng)論 1 300
  • 那天粤铭,我揣著相機(jī)與錄音,去河邊找鬼杂靶。 笑死梆惯,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的伪煤。 我是一名探鬼主播加袋,決...
    沈念sama閱讀 40,122評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼抱既!你這毒婦竟也來了职烧?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,970評(píng)論 0 275
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎蚀之,沒想到半個(gè)月后蝗敢,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,403評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡足删,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,596評(píng)論 3 334
  • 正文 我和宋清朗相戀三年寿谴,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片失受。...
    茶點(diǎn)故事閱讀 39,769評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡讶泰,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出拂到,到底是詐尸還是另有隱情痪署,我是刑警寧澤,帶...
    沈念sama閱讀 35,464評(píng)論 5 344
  • 正文 年R本政府宣布兄旬,位于F島的核電站狼犯,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏领铐。R本人自食惡果不足惜悯森,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,075評(píng)論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望绪撵。 院中可真熱鬧瓢姻,春花似錦、人聲如沸莲兢。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)改艇。三九已至收班,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間谒兄,已是汗流浹背摔桦。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留承疲,地道東北人邻耕。 一個(gè)月前我還...
    沈念sama閱讀 47,831評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像燕鸽,于是被迫代替她去往敵國(guó)和親兄世。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,678評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容