iOS开发中用到的一些方法总结

```

#import YJCUtility

@interface YJCUtility : NSObject

/*

 *获取应用的window

 */

+ (UIWindow *)getcurrentAppWindow;

/*

 *获取view映射到window的rect

 *@prama view:需要映射的view

 */

+ (CGRect)getRectToWindowWithView:(UIView *)view;

#pragma mark ----- json和字典的互转

/*

 *数据转成jsonString

 */

+ (NSString *)objectTojsonString:(id)object;

/*!

 *@brief 把格式化的JSON格式的字符串转换成字典

 *@param jsonString JSON格式的字符串

 *@return 返回字典

 */

+ (id)dictionaryWithJsonString:(NSString *)jsonString;

//数组或者字典转成JSON格式的字符串

+ (NSString *)dictionaryOrArrayToJson:(id)object;

//json转字典或者数组

+ (id)toArrayOrNSDictionary:(NSData *)jsonData;

+ (NSData *)toJSONData:(id)theData;

#pragma mark - 文字的处理

/*

 *计算多行文字的高度

 *@param string 文本内容

 *@param font  字体大小

 *@return 返货CGFloat类型

 */

+ (CGFloat)heightWithTextString:(NSString *)string textWidth:(CGFloat)width textFont:(CGFloat)font;

//有个行间距

+ (CGFloat)heightWithTextString:(NSString *)string textWidth:(CGFloat)width lineSpacing:(CGFloat)lineSpa textFont:(CGFloat)font;

/*

 *计算一行文字的宽度

 *@param string 文本内容

 *@param font 字体大小

 *@return 返回CGRect类型

 */

+ (CGSize)WidthWithTextString:(NSString *)string textFont:(CGFloat)font;

/*

 *字符串用空格分隔

 *@param str 传入的字符串

 *@param len 分隔的长度

 *@return str 输出分隔好的字符串

 */

+ (NSString *)stringSeparateBySpaceString:(NSString *)str WithLenth:(NSInteger)len;

/*

 *移除字符串里的空格符

 *@param str传入的字符串

 *@return 输出分割好的字符串

 */

+ (NSString *)stringRemoveSpaceWithString:(NSString *)str;

/*

 *判断字符串中包含emoji表情

 *prama string待检测的字符串

 */

+ (BOOL)stringContainEmoji:(NSString *)string;

/*

 *判断一个字符串是不是汉字、数字和英文字母

 *@param newName待检测的字符串

 */

+ (BOOL)isRightName:(NSString *)newName;

#pragma mark ---- 电话号码的处理

/*

 *把电话号码的中间四位用*代替

 */

+ (NSString *)starMobileWithMobile:(NSString *)mobile;

/*

 *判断身份证号

 */

+ (BOOL)isIdCardNo:(NSString *)identityCard;

//判断一串数字是不是电话号码

+ (BOOL)isMobileNumber:(NSString *)mobileNum;

#pragma mark ---- 银行卡号的处理

/*

 *银行卡获取尾号后4位

 */

+ (NSString *)getBankCarkLastNumber:(NSString *)cardNumber;

/**

 *  银行卡显示前后四位,中间7个*代替

 */

+ (NSString*) starBankCardWithCardNumber:(NSString*) cardNumber;

#pragma mark- 设备的属性

//判断是不是4或者4s的

+ (BOOL) isFour;

//判断是不是plus

+ (BOOL) isPlus;

#pragma mark- 图片处理

/*

 *图片等比压缩

 *压缩后的图片是正方形

 *@rama image:原图 width:压缩后的宽和高

 */

+ (UIImage *)compressImage:(UIImage *)image Width:(CGFloat)width;

/**

 *  图片截取

 *  截取后的图片是正方形

 *  @prama image:原图  mCGRect:截取的frame centerBool:是否从中间截取

 */

+(UIImage*)getSubImage:(UIImage *)image mCGRect:(CGRect)mCGRect centerBool:(BOOL)centerBool;

/**

 *  购物车点击的飞行动画

 */

+ (void)flyAnimationWithStartPoint:(CGPoint)pos;

#pragma mark- 获取当前VC的方法

+ (UIViewController *)getCurrentVC;

#pragma mark- 时间转换函数

/**

 *  NSDate转成NSString

 */

+ (NSString *)stringFenFromDate:(NSDate *)date;

/**

 *  dateStr(yyyy-MM-dd HH:mm:ss)转成没有秒(yyyy-MM-dd HH:mm:ss)

 */

+ (NSString *)stringFenFromDateStr:(NSString *)dateStr;

/**

 * dateStr yyyy-MM-dd HH:mm:ss转成yyyy.MM.dd

 */

+ (NSString *)stringPoint1FromDateStr:(NSString *)dateStr;

/**

 * dateStr yyyy-MM-dd转成yyyy.MM.dd

 */

+ (NSString *)stringPoint2FromDateStr:(NSString *)dateStr;

/**

 *  按照数字选取,无小数则取整数,有小数取两位小数

 */

+ (NSString *)stringWithDoubleValue:(double)value;

/**

 *  按照数字选取,无小数则取整数,有小数取两位小数

 */

+ (NSString *)notRounding:(NSDecimalNumber *)price afterPoint:(NSInteger)position;

/**

 *  保留一位小数

 */

+ (NSString *)stringStyleOneWithValue:(double)value;

/*

 *截屏

 */

+ (UIImage *)screenShotFromView:(UIView *)targetView;

//绘制虚线

+ (CALayer *)drawYAxsiLineStart:(CGPoint)start End:(CGPoint)end stroke:(UIColor *)stroke lineW:(CGFloat)width pw:(CGFloat)pw lw:(CGFloat)lw;

+ (CALayer *)drawYAxsiLineStart:(CGPoint)start End:(CGPoint)end;

@end

```

#define HK_DEBUG_LOG(...)    NSLog(__VA_ARGS__)

#define MAXFLOAT    0x1.fffffep+127f

#define MainScreenSize_W  [[UIScreen mainScreen] bounds].size.width

#define MainScreenSize_H  [UIScreen mainScreen].bounds.size.height

#define UIColorFromRGBA(rgbValue, alphaValue) \

[UIColor \

colorWithRed:((float)((rgbValue &0xFF0000) >>16))/255.0\

green:((float)((rgbValue &0x00FF00) >>8))/255.0\

blue:((float)(rgbValue &0x0000FF))/255.0\

alpha:alphaValue]

/**

 *  app 主色调 黄色

 */

#define kBaseColor      (UIColorFromRGBA(0xff9a00,1.0))

#import "YJCUtility.h"

#import

@implementation YJCUtility

//获取应用的window

+ (UIWindow *)getcurrentAppWindow

{

    UIWindow * window = window = [[UIApplication sharedApplication].windows objectAtIndex:0];

    returnwindow;

}

/**

 * 获取view 映射到window上的rect

 * @prama view:需要影射的view

 */

+ (CGRect)getRectToWindowWithView:(UIView *)view

{

    [[[[UIApplication sharedApplication] windows] objectAtIndex:0] makeKeyWindow];

    UIWindow * window = [UIApplication sharedApplication].keyWindow;

    if(!window) {

        window = [[UIApplication sharedApplication].windows objectAtIndex:0];

    }

    CGRect rect = [view convertRect:view.bounds toView:window];

    returnrect;

}

/*

 *数据转成jsonString(比如字典转成一个data串儿)

 */

//举例使用方法

/*

 *NSDictionary *dataDict = @{@"merchantId":[NSNumber numberWithInt:self.orderVeritifyModel.merchantId],

                             @"userId":userIdStr,

                             @"loginToken":[UserInfoManager sharedInstance].token,

                             @"userAddressId":[NSNumber numberWithLong:self.orderVeritifyModel.addressModel.addressId],

                             @"orderPayType":[NSNumber numberWithInt:_userSelectPayType],

                             @"expectedArrivalTime":_userSelectExpectedArrivalType

                            };

 NSString *data = [MGJUtility objectTojsonString:dataDict];

 NSDictionary *mDict = @{@"latitude": @([UserLocationManager sharedInstance].userSettedLoction.latitude),

                         @"longitude": @([UserLocationManager sharedInstance].userSettedLoction.longitude),

                         @"data":data

                        };

  NSDictionary *tmp_dict = @{@"params":mDict};

 */

+ (NSString *)objectTojsonString:(id)object

{

    NSString * jsonString = [[NSString alloc] init];

    NSError * error;

    NSData * jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&error];

    if(!jsonData) {

        HK_DEBUG_LOG(@"error: %@", error);

    }

    else{

        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    }

    NSMutableString * mutStr = [NSMutableString stringWithString:jsonString];

    NSRange range = {0,jsonString.length};

    [mutStr replaceOccurrencesOfString:@" "

                            withString:@""

                            options:NSLiteralSearch range:range];

    NSRange range1 = {0,mutStr.length};

    [mutStr replaceOccurrencesOfString:@"\n"

                            withString:@""

                               options:NSLiteralSearch range:range1];

    returnmutStr;

}

#pragma mark- json和字典的互转函数

/*!

 *@brief 把格式化的JSON格式的字符串转换成字典

 *@prama jsonString JSON格式的字符串

 *@return 返回字典

 */

+ (id)dictionaryWithJsonString:(NSString *)jsonString

{

    if(jsonString ==nil|| jsonString.length ==0) {

        returnnil;

    }

    NSData * jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

    NSError * err;

    iddic = [NSJSONSerialization JSONObjectWithData:jsonData

                                              options:NSJSONReadingMutableContainers

                                                error:&err];

    if(err) {

        HK_DEBUG_LOG(@"json解析失败:%@",err);

        returnnil;

    }

    returndic;

}

//数组或者字典转成JSON格式的字符串

+ (NSString *)dictionaryOrArrayToJson:(id)object

{

    NSError * paraseError =nil;

    NSData * jsonData = [NSJSONSerialization dataWithJSONObject:object

                                                        options:NSJSONWritingPrettyPrinted

                                                          error:¶seError];

    return[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

}

//json转字典或者数组

+ (id)toArrayOrNSDictionary:(NSData *)jsonData

{

    NSError * error =nil;

    idjsonObject = [NSJSONSerialization JSONObjectWithData:jsonData

                                                    options:NSJSONReadingAllowFragments

                                                      error:&error];

    if(jsonObject !=nil&& error ==nil) {

        returnjsonObject;

    }else{

        //解析错误

        returnnil;

    }

}

+ (NSData *)toJSONData:(id)theData

{

    NSError * err =nil;

    NSData * jsonData = [NSJSONSerialization dataWithJSONObject:theData

                                                        options:NSJSONWritingPrettyPrinted

                                                          error:&err];

    if([jsonData length] >0&& err ==nil) {

        returnjsonData;

    }else{

        returnnil;

    }

}

/*

 *计算多行文字的高度

 *@param string 文本内容

 *@param font  字体大小

 *@return 返货CGFloat类型

 */

+ (CGFloat)heightWithTextString:(NSString *)string textWidth:(CGFloat)width textFont:(CGFloat)font

{

    CGRect rect = [string boundingRectWithSize:CGSizeMake(width,10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]}context:nil];

    returnrect.size.height +1;

}

+ (CGFloat)heightWithTextString:(NSString *)string textWidth:(CGFloat)width lineSpacing:(CGFloat)lineSpa textFont:(CGFloat)font

{

    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];

    paragraphStyle.lineSpacing = lineSpa;

    CGRect rect = [string boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font],NSParagraphStyleAttributeName:paragraphStyle}context:nil];

    returnrect.size.height +1;

}

/*

 *计算一行文字的宽度

 *@param string 文本内容

 *@param font 字体大小

 *@return 返回CGRect类型

 */

+ (CGSize)WidthWithTextString:(NSString *)string textFont:(CGFloat)font

{

    CGSize size = [string sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]}];

    returnsize;

}

/*

 *字符串用空格分隔

 *@param str 传入的字符串

 *@param len 分隔的长度

 *@return str 输出分隔好的字符串

 */

+ (NSString *)stringSeparateBySpaceString:(NSString *)str WithLenth:(NSInteger)len

{

    if(str ==nil) {

        return@"";

    }

    NSMutableString * tmp_str = [[NSMutableString alloc] initWithString:str];

    NSInteger index = len;

    while(tmp_str.length > index) {

        [tmp_str insertString:@" "atIndex:index];

        index += (len+1);

    }

    returntmp_str;

}

/*

 *移除字符串里的空格符

 *@param str传入的字符串

 *@return 输出分割好的字符串

 */

+ (NSString *)stringRemoveSpaceWithString:(NSString *)str

{

    if(str ==nil) {

        return@"";

    }

    NSString * tmp_str = str;

    tmp_str = [tmp_str stringByReplacingOccurrencesOfString:@" "withString:@""];

    returntmp_str;

}

/*

 *判断字符串中包含emoji表情

 *prama string待检测的字符串

 */

+ (BOOL)stringContainEmoji:(NSString *)string

{

    __blockBOOLreturnValue =NO;

    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *_Nullablesubstring, NSRange substringRange, NSRange enclosingRange,BOOL*_Nonnullstop) {

        constunichar hs = [substring characterAtIndex:0];


        if(0xd800) {

            if(0xd800<= hs && hs<=0xdbff) {

                if(substring.length >1) {

                    constunichar ls =[substring characterAtIndex:1];

                    constintuc = ((hs -0xd800) *0x400)+(ls-0xdc00) +0x10000;

                    if(0x1d000<= uc && uc <=0x1f77f) {

                        returnValue =YES;

                    }

                }

            }elseif(substring.length >1) {

                constunichar ls = [substring characterAtIndex:1];

                if(ls ==0x20e3) {

                    returnValue =YES;

                }

            }else{

                if(0x2100<= hs && hs <=0x27ff) {

                    returnValue =YES;

                }elseif(0x2B05<= hs && hs <=0x2b07) {

                    returnValue =YES;

                }elseif(0x2934<= hs && hs <=0x2935) {

                    returnValue =YES;

                }elseif(0x3297<= hs && hs <=0x3299) {

                    returnValue =YES;

                }elseif(hs ==0xa9|| hs ==0xae|| hs ==0x303d|| hs ==0x3030|| hs ==0x2b55|| hs ==0x2b1c|| hs ==0x2b1b|| hs ==0x2b50) {

                    returnValue =YES;

                }

            }

        }

    }];

    returnreturnValue;

}

/*

 *判断一个字符串是不是汉字、数字和英文字母

 *@param newName待检测的字符串

 */

+ (BOOL)isRightName:(NSString *)newName

{

    //“^.{5}$”:表示任意1个长度为5的字符串;只能输入由数字和26个英文字母组成的字符串^[A-Za-z0-9]+$(只能输入汉字:”^[\u4e00-\u9fa5]{0,}$”)

    NSString * NAME =@"^[a-zA-Z0-9\u4e00-\u9fa5_]{1,30}$";

    NSPredicate * userName = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", NAME];

    if([userName evaluateWithObject:newName] ==YES) {

        returnYES;

    }else{

        returnNO;

    }

}

/*

 *把电话号码的中间四位用*代替

 */

+ (NSString *)starMobileWithMobile:(NSString *)mobile

{

    NSString * tmp_mobile = mobile;

    if(mobile.length >=7) {

        tmp_mobile = [tmp_mobile stringByReplacingCharactersInRange:NSMakeRange(3,4) withString:@"****"];

    }

    returntmp_mobile;

}

/*

 *判断身份证号

 */

+ (BOOL)isIdCardNo:(NSString *)identityCard

{

    BOOLflag;

    NSString *regex2 =@"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";

    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];

    flag = [identityCardPredicate evaluateWithObject:identityCard];


    //如果通过该验证,说明身份证格式正确,但准确性还需计算

    if(flag) {

        if(identityCard.length==18) {

            //将前17位加权因子保存在数组里

            NSArray * idCardWiArray =@[@"7",@"9",@"10",@"5",@"8",@"4",@"2",@"1",@"6",@"3",@"7",@"9",@"10",@"5",@"8",@"4",@"2"];


            //这是除以11后,可能产生的11位余数、验证码,也保存成数组

            NSArray * idCardYArray =@[@"1",@"0",@"10",@"9",@"8",@"7",@"6",@"5",@"4",@"3",@"2"];


            //用来保存前17位各自乖以加权因子后的总和


            NSInteger idCardWiSum =0;

            for(inti =0;i <17;i++) {

                NSInteger subStrIndex = [[identityCard substringWithRange:NSMakeRange(i,1)] integerValue];

                NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];


                idCardWiSum+= subStrIndex * idCardWiIndex;

            }

            //计算出校验码所在数组的位置

            NSInteger idCardMod=idCardWiSum%11;

            //得到最后一位身份证号码

            NSString * idCardLast= [identityCard substringWithRange:NSMakeRange(17,1)];

            //如果等于2,则说明校验码是10,身份证号码最后一位应该是X

            if(idCardMod==2) {

                if([idCardLast isEqualToString:@"X"]||[idCardLast isEqualToString:@"x"]) {

                    returnflag;

                }else{

                    flag =  NO;

                    returnflag;

                }

            }else  {

                //用计算出的验证码与最后一位身份证号码匹配,如果一致,说明通过,否则是无效的身份证号码

                if([idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]]) {

                    returnflag;

                }else{

                    flag =  NO;

                    returnflag;

                }

            }

        }else{

            flag =  NO;

            returnflag;

        }

    }else{

        returnflag;

    }

}

//判断一串数字是不是电话号码

+ (BOOL)isMobileNumber:(NSString *)mobileNum

{

    NSString * MOBILE =  @"^[1][3456789][0-9]{9}$";//普通手机号码去年加上了166的号了

    NSString * PHS =@"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";//座机或者小灵通

    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];

    NSPredicate *regextestPHS = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", PHS];

    if([regextestmobile evaluateWithObject:mobileNum] ==YES) {

        returnYES;

    }elseif([regextestPHS evaluateWithObject:mobileNum] ==YES){

        returnYES;

    }else{

        returnNO;

    }

}

/*

 *银行卡获取尾号后4位

 */

+ (NSString *)getBankCarkLastNumber:(NSString *)cardNumber

{

    NSString * tmp_str =@"";

    if(cardNumber.length >=4) {

        tmp_str = [cardNumber substringFromIndex:cardNumber.length -4];

    }

    returntmp_str;

}

/**

 *  银行卡显示前后四位,中间7个*代替

 */

+ (NSString*) starBankCardWithCardNumber:(NSString*) cardNumber

{

    NSString *temp_str = cardNumber;

    if(cardNumber.length >=7) {

        temp_str = [temp_str stringByReplacingCharactersInRange:NSMakeRange(4, cardNumber.length-8) withString:@"*******"];

    }


    returntemp_str;

}

//判断是不是4或者4s的根据屏幕宽判断

+ (BOOL) isFour

{

    staticdispatch_once_t one;

    staticBOOLisFour =NO;

    dispatch_once(&one, ^{

        if(((NSInteger)MainScreenSize_H) %480==0&&((NSInteger)MainScreenSize_W) %320==0) {

            isFour =YES;

        }

    });

    returnisFour;

}

//判断是不是plus

+ (BOOL) isPlus

{

    staticdispatch_once_t one;

    staticBOOLisPlus =NO;

    NSString * curIphoneType = [YJCUtility iphoneType];

    dispatch_once(&one, ^{

        if([curIphoneType isEqualToString:@"iPhone 6 Plus"]||

            [curIphoneType isEqualToString:@"iPhone 6s Plus"]||

            [curIphoneType isEqualToString:@"iPhone 7 Plus"]) {

            isPlus =YES;

        }

    });

    returnisPlus;

}

+ (NSString *)iphoneType

{

    structutsname systemInfo;


    uname(&systemInfo);


    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];

    if([platform isEqualToString:@"iPhone1,1"])return@"iPhone 2G";

    if([platform isEqualToString:@"iPhone1,2"])return@"iPhone 3G";

    if([platform isEqualToString:@"iPhone2,1"])return@"iPhone 3GS";

    if([platform isEqualToString:@"iPhone3,1"])return@"iPhone 4";

    if([platform isEqualToString:@"iPhone3,2"])return@"iPhone 4";

    if([platform isEqualToString:@"iPhone3,3"])return@"iPhone 4";

    if([platform isEqualToString:@"iPhone4,1"])return@"iPhone 4S";

    if([platform isEqualToString:@"iPhone5,1"])return@"iPhone 5";

    if([platform isEqualToString:@"iPhone5,2"])return@"iPhone 5";

    if([platform isEqualToString:@"iPhone5,3"])return@"iPhone 5c";

    if([platform isEqualToString:@"iPhone5,4"])return@"iPhone 5c";

    if([platform isEqualToString:@"iPhone6,1"])return@"iPhone 5s";

    if([platform isEqualToString:@"iPhone6,2"])return@"iPhone 5s";

    if([platform isEqualToString:@"iPhone7,1"])return@"iPhone 6 Plus";

    if([platform isEqualToString:@"iPhone7,2"])return@"iPhone 6";

    if([platform isEqualToString:@"iPhone8,1"])return@"iPhone 6s";

    if([platform isEqualToString:@"iPhone8,2"])return@"iPhone 6s Plus";

    if([platform isEqualToString:@"iPhone8,4"])return@"iPhone SE";

    if([platform isEqualToString:@"iPhone9,1"])return@"iPhone 7";

    if([platform isEqualToString:@"iPhone9,2"])return@"iPhone 7 Plus";

    if([platform isEqualToString:@"iPod1,1"])  return@"iPod Touch 1G";

    if([platform isEqualToString:@"iPod2,1"])  return@"iPod Touch 2G";

    if([platform isEqualToString:@"iPod3,1"])  return@"iPod Touch 3G";

    if([platform isEqualToString:@"iPod4,1"])  return@"iPod Touch 4G";

    if([platform isEqualToString:@"iPod5,1"])  return@"iPod Touch 5G";

    if([platform isEqualToString:@"iPad1,1"])  return@"iPad 1G";

    if([platform isEqualToString:@"iPad2,1"])  return@"iPad 2";

    if([platform isEqualToString:@"iPad2,2"])  return@"iPad 2";

    if([platform isEqualToString:@"iPad2,3"])  return@"iPad 2";

    if([platform isEqualToString:@"iPad2,4"])  return@"iPad 2";

    if([platform isEqualToString:@"iPad2,5"])  return@"iPad Mini 1G";

    if([platform isEqualToString:@"iPad2,6"])  return@"iPad Mini 1G";

    if([platform isEqualToString:@"iPad2,7"])  return@"iPad Mini 1G";

    if([platform isEqualToString:@"iPad3,1"])  return@"iPad 3";

    if([platform isEqualToString:@"iPad3,2"])  return@"iPad 3";

    if([platform isEqualToString:@"iPad3,3"])  return@"iPad 3";

    if([platform isEqualToString:@"iPad3,4"])  return@"iPad 4";

    if([platform isEqualToString:@"iPad3,5"])  return@"iPad 4";

    if([platform isEqualToString:@"iPad3,6"])  return@"iPad 4";

    if([platform isEqualToString:@"iPad4,1"])  return@"iPad Air";

    if([platform isEqualToString:@"iPad4,2"])  return@"iPad Air";

    if([platform isEqualToString:@"iPad4,3"])  return@"iPad Air";

    if([platform isEqualToString:@"iPad4,4"])  return@"iPad Mini 2G";

    if([platform isEqualToString:@"iPad4,5"])  return@"iPad Mini 2G";

    if([platform isEqualToString:@"iPad4,6"])  return@"iPad Mini 2G";

    if([platform isEqualToString:@"i386"])      return@"iPhone Simulator";

    if([platform isEqualToString:@"x86_64"])    return@"iPhone Simulator";

    returnplatform;

}

/*

 *图片等比压缩

 *压缩后的图片是正方形

 *@rama image:原图 width:压缩后的宽和高

 */

+ (UIImage *)compressImage:(UIImage *)image Width:(CGFloat)width

{

    floatscaleSize = image.size.height / image.size.width;

    if(width ==240) {

        UIGraphicsBeginImageContext(CGSizeMake(240,240*scaleSize));

        [image drawInRect:CGRectMake(0,0,240,240*scaleSize)];

    }else{

        UIGraphicsBeginImageContext(CGSizeMake(720,720*scaleSize));

        [image drawInRect:CGRectMake(0,0,720,720*scaleSize)];

    }

    UIImage * scaleImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    returnscaleImage;

}

/**

 *  图片截取

 *  截取后的图片是正方形

 *  @prama image:原图  mCGRect:截取的frame centerBool:是否从中间截取

 */

+(UIImage*)getSubImage:(UIImage *)image mCGRect:(CGRect)mCGRect centerBool:(BOOL)centerBool

{

    /*如若centerBool为Yes则是由中心点取mCGRect范围的图片*/

    floatimgwidth = image.size.width;

    floatimgheight = image.size.height;

    floatviewwidth = mCGRect.size.width;

    floatviewheight = mCGRect.size.height;

    CGRect rect;

    if(centerBool)

        rect = CGRectMake((imgwidth-viewwidth)/2, (imgheight-viewheight)/2, viewwidth, viewheight);

    else{

        if(viewheight < viewwidth) {

            if(imgwidth <= imgheight) {

                rect = CGRectMake(0,0, imgwidth, imgwidth*viewheight/viewwidth);

            }else{

                floatwidth = viewwidth*imgheight/viewheight;

                floatx = (imgwidth - width)/2;

                if(x >0) {

                    rect = CGRectMake(x,0, width, imgheight);

                }else{

                    rect = CGRectMake(0,0, imgwidth, imgwidth*viewheight/viewwidth);

                }

            }

        }else{

            if(imgwidth <= imgheight) {

                floatheight = viewheight*imgwidth/viewwidth;

                if(height < imgheight) {

                    rect = CGRectMake(0,0, imgwidth, height);

                }else{

                    rect = CGRectMake(0,0, viewwidth*imgheight/viewheight, imgheight);

                }

            }else{

                floatwidth = viewwidth*imgheight/viewheight;

                if(width < imgwidth) {

                    floatx = (imgwidth - width)/2;

                    rect = CGRectMake(x,0, width, imgheight);

                }else{

                    rect = CGRectMake(0,0, imgwidth, imgheight);

                }

            }

        }

    }

    CGImageRef subImageRef = CGImageCreateWithImageInRect(image.CGImage, rect);

    CGRect smallBounds = CGRectMake(0,0, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));


    UIGraphicsBeginImageContext(smallBounds.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextDrawImage(context, smallBounds, subImageRef);

    UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];


    UIGraphicsEndImageContext();

    CGImageRelease(subImageRef);

    returnsmallImage;

}

/**

 *  购物车点击的飞行动画//落点根据实际需求进行修改

 */

+ (void)flyAnimationWithStartPoint:(CGPoint)pos

{

    [selfdoCartAnimationFrom:CGPointMake(pos.x, pos.y) toPos:CGPointMake(28, MainScreenSize_H -22)];

}

+ (void) doCartAnimationFrom:(CGPoint)fromPos toPos:(CGPoint)toPos

{


    CALayer *layer = [[CALayer alloc] init];

    layer.frame = CGRectMake(10, MainScreenSize_H,20,20);

    layer.masksToBounds =YES;

    layer.cornerRadius =10;

    layer.backgroundColor = kBaseColor.CGColor;//kBaseColor主色调这里暂定的黄色,在宏定义里边进行修改

    UIWindow* window = [UIApplication sharedApplication].keyWindow;

    [window.layer addSublayer:layer];

    CAKeyframeAnimation *animation=[CAKeyframeAnimation animationWithKeyPath:@"position"];

    animation.duration =0.4f;

    animation.removedOnCompletion =YES;

    animation.fillMode = kCAFillModeRemoved;

    animation.repeatCount =1;// repeat forever

    animation.calculationMode = kCAAnimationCubicPaced;

    CGMutablePathRef curvedPath = CGPathCreateMutable();

    CGPathMoveToPoint(curvedPath,NULL, fromPos.x, fromPos.y);

    CGPathAddQuadCurveToPoint(curvedPath,NULL,112,184, toPos.x, toPos.y);


    animation.path = curvedPath;


    [layer addAnimation:animation forKey:nil];

    CGPathRelease(curvedPath);

    [layer performSelector:@selector(removeFromSuperlayer) withObject:nilafterDelay:0.4];

}

//获取当前VC的方法

+ (UIViewController *)getCurrentVC

{

    UIViewController * result =nil;

    UIWindow * window = [[UIApplication sharedApplication] keyWindow];

    if(window.windowLevel != UIWindowLevelNormal) {

        NSArray * windows = [[UIApplication sharedApplication] windows];

        for(UIWindow * tmpWininwindows) {

            if(tmpWin.windowLevel == UIWindowLevelNormal) {

                window = tmpWin;

                break;

            }

        }

    }

    UIView * frontView = [[window subviews] objectAtIndex:0];

    idnextResponder = [frontView nextResponder];

    if([nextResponder isKindOfClass:[UIViewController class]])

        result = nextResponder;

    else

        result = window.rootViewController;

    returnresult;

}

#pragma mark- 时间转换函数

/**

 *  NSDate转成NSString

 */

+ (NSString *)stringFenFromDate:(NSDate *)date

{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    //zzz表示时区,zzz可以删除,这样返回的日期字符将不包含时区信息。

    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];


    NSString *destDateString = [dateFormatter stringFromDate:date];

    returndestDateString;

}

/**

 *  dateStr(yyyy-MM-dd HH:mm:ss)转成没有秒(yyyy-MM-dd HH:mm:ss)

 */

+ (NSString *)stringFenFromDateStr:(NSString *)dateStr

{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSDate *date = [dateFormatter dateFromString:dateStr];

    return[YJCUtility stringFenFromDate:date];

}

/**

 * dateStr yyyy-MM-dd HH:mm:ss转成yyyy.MM.dd

 */

+ (NSString *)stringPoint1FromDateStr:(NSString *)dateStr

{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSDate *date = [dateFormatter dateFromString:dateStr];

    [dateFormatter setDateFormat:@"yyyy.MM.dd"];

    NSString *destDateString = [dateFormatter stringFromDate:date];

    returndestDateString;

}

/**

 * dateStr yyyy-MM-dd转成yyyy.MM.dd

 */

+ (NSString *)stringPoint2FromDateStr:(NSString *)dateStr

{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@"yyyy-MM-dd"];

    NSDate *date = [dateFormatter dateFromString:dateStr];

    [dateFormatter setDateFormat:@"yyyy.MM.dd"];

    NSString *destDateString = [dateFormatter stringFromDate:date];

    returndestDateString;

}

/**

 *  按照数字选取,无小数则取整数,有小数取两位小数

 */

+ (NSString *)stringWithDoubleValue:(double)value

{

    if(fmod(value,1)==0) {

        return[NSString stringWithFormat:@"%.0f",value];

    }elseif(fmod(value*10,1)==0) {

        return[NSString stringWithFormat:@"%.1f",value];

    }else{

        return[NSString stringWithFormat:@"%.2f",value];

    }

}

/**

 *@brief  截取指定小数位的值

 *@prama  price需要转化的数据

 *@prama  position有效小数位

 *@return  截取后数据

 */

+ (NSString *)notRounding:(NSDecimalNumber *)price afterPoint:(NSInteger)position

{

    NSDecimalNumberHandler* roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:position raiseOnExactness:NOraiseOnOverflow:NOraiseOnUnderflow:NOraiseOnDivideByZero:NO];

    NSDecimalNumber *roundedOunces;

    roundedOunces = [price decimalNumberByRoundingAccordingToBehavior:roundingBehavior];


    return[NSString stringWithFormat:@"%@",roundedOunces];

}

/*

 *截屏

 */

+ (UIImage *)screenShotFromView:(UIView *)targetView

{

    // 背景图片 总的大小

    CGSize size = [UIScreen mainScreen].bounds.size;

    UIGraphicsBeginImageContext(size);

    // 开启上下文,使用参数之后,截出来的是原图(YES  0.0 质量高)

    UIGraphicsBeginImageContextWithOptions(size,YES,0.0);

    CGRect rect = CGRectMake(0,0, size.width, size.height);

    //注:iOS7以后renderInContext:由drawViewHierarchyInRect:afterScreenUpdates:替代

    [targetView drawViewHierarchyInRect:rect afterScreenUpdates:NO];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    // 千万记得,结束上下文(移除栈顶上下文)

    UIGraphicsEndImageContext();

    returnimage;

}

//绘制虚线-----pw是点的宽度point width;lw是空隙的宽度

+ (CALayer *)drawYAxsiLineStart:(CGPoint)start End:(CGPoint)end stroke:(UIColor *)stroke lineW:(CGFloat)width pw:(CGFloat)pw lw:(CGFloat)lw

{

    UIBezierPath * yAxisPath = [[UIBezierPath alloc] init];

    [yAxisPath moveToPoint:CGPointMake(start.x, start.y)];

    [yAxisPath addLineToPoint:CGPointMake(end.x, end.y)];


    CAShapeLayer * yAxisLayer = [CAShapeLayer layer];

    [yAxisLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:pw],[NSNumber numberWithInt:lw],nil]];// 设置线为虚线,数组的第一个值是点的宽度,第二个是空隙的宽度

    yAxisLayer.lineWidth = width;

    yAxisLayer.strokeColor = stroke.CGColor;

    yAxisLayer.path = yAxisPath.CGPath;

    returnyAxisLayer;

}

//举例

+ (CALayer *)drawYAxsiLineStart:(CGPoint)start End:(CGPoint)end

{

    return[selfdrawYAxsiLineStart:start End:end stroke:UIColorFromRGBA(0xc5c5c5,1.0) lineW:0.5pw:1.5lw:2.0];

}

@end

```

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,332评论 5 475
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,930评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,204评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,348评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,356评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,447评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,862评论 3 394
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,516评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,710评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,518评论 2 318
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,582评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,295评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,848评论 3 306
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,881评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,121评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,737评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,280评论 2 341

推荐阅读更多精彩内容