// // myHleper.m // myWatch // // Created by xTT on 16/3/16. // Copyright © 2016年 xTT. All rights reserved. // #import "myHelper.h" #import #import "User.h" #import "Device.h" //#import "SVProgressHUD.h" @implementation myHelper + (UIImage *)getImageWithName:(NSString *)name{ UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%@%@",THEME_NAME,name]]; if (!image) { return [UIImage imageNamed:name]; }else{ return image; } } + (UIFont *)fixFoneSize:(NSInteger)size font:(UIFont *)font{ return [font fontWithSize:size * SWIDTH / 320]; } + (NSString *)getDateFormatWithStr:(NSString *)dateFormat date:(NSDate *)date{ NSDateFormatter*dateFormatter = [[NSDateFormatter alloc]init]; [dateFormatter setDateFormat:dateFormat]; return [dateFormatter stringFromDate:date]; } + (NSString *)getDateFormatWithStr:(NSString *)dateFormat timeInterval:(NSTimeInterval)timeInterval{ return [self getDateFormatWithStr:dateFormat date:[NSDate dateWithTimeIntervalSince1970:timeInterval]]; } + (NSDate *)getDateWithStr:(NSString *)dateString dateFormat:(NSString *)dateFormat{ dateString = [dateString stringByReplacingOccurrencesOfString:@"T" withString:@" "]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat: dateFormat]; NSDate *destDate= [dateFormatter dateFromString:dateString]; return destDate; } ///< 获取当前时间的: 前一周(day:-7)丶前一个月(month:-30)丶前一年(year:-1)的时间 NSDate + (NSDate *)ddpGetExpectTimestamp:(NSInteger)year month:(NSUInteger)month day:(NSUInteger)day { ///< 当前时间 NSDate *currentdata = [NSDate date]; ///< NSCalendar -- 日历类,它提供了大部分的日期计算接口,并且允许您在NSDate和NSDateComponents之间转换 NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; /* ///< NSDateComponents:时间容器,一个包含了详细的年月日时分秒的容器。 ///< 下例:获取指定日期的年,月,日 NSDateComponents *comps = nil; comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentdata]; NSLog(@"年 year = %ld",comps.year); NSLog(@"月 month = %ld",comps.month); NSLog(@"日 day = %ld",comps.day);*/ NSDateComponents *datecomps = [[NSDateComponents alloc] init]; [datecomps setYear:year?:0]; [datecomps setMonth:month?:0]; [datecomps setDay:day?:0]; ///< dateByAddingComponents: 在参数date基础上,增加一个NSDateComponents类型的时间增量 NSDate *calculatedate = [calendar dateByAddingComponents:datecomps toDate:currentdata options:0]; // ///< 打印推算时间 // NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; // [formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; // NSString *calculateStr = [formatter stringFromDate:calculatedate]; // // xLog(@"calculateStr 推算时间: %@",calculateStr ); // // ///< 预期的推算时间 // NSString *result = [NSString stringWithFormat:@"%ld", (long)[calculatedate timeIntervalSince1970]]; return calculatedate; } + (BOOL)isEqualImage:(UIImage *)image1 image2:(UIImage *)image2{ NSData *data1 = UIImagePNGRepresentation(image1); NSData *data = UIImagePNGRepresentation(image2); if ([data isEqual:data1]) { return YES; } return NO; } + (UIColor *)colorWithHexString:(NSString *)color { NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString]; // String should be 6 or 8 characters if ([cString length] < 6) { return [UIColor clearColor]; } // 判断前缀 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]; // Scan values unsigned int r, g, b; [[NSScanner scannerWithString:rString] scanHexInt:&r]; [[NSScanner scannerWithString:gString] scanHexInt:&g]; [[NSScanner scannerWithString:bString] scanHexInt:&b]; return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f]; } #pragma mark 二维码 URL获取 参数 + (NSMutableDictionary *)getDicWithUrl:(NSString *)urlStr{ //获取问号的位置,问号后是参数列表 NSRange range = [urlStr rangeOfString:@"?"]; if (range.location != NSNotFound) { //获取参数列表 NSString *propertys = [urlStr substringFromIndex:(int)(range.location+1)]; //进行字符串的拆分,通过&来拆分,把每个参数分开 NSArray *subArray = [propertys componentsSeparatedByString:@"&"]; //把subArray转换为字典 //tempDic中存放一个URL中转换的键值对 NSMutableDictionary *tempDic = [NSMutableDictionary dictionary]; [subArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) { //在通过=拆分键和值 NSArray *dicArray = [obj componentsSeparatedByString:@"="]; if (dicArray.count >= 2) { //给字典加入元素 [tempDic setObject:dicArray[1] forKey:dicArray[0]]; } }]; return tempDic; } return nil; } #pragma mark 将头像图片加上边框 + (UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2 { UIGraphicsBeginImageContextWithOptions(image2.size, NO, 2.0); //Draw 头像 [image1 drawInRect:CGRectMake(0, 0, image1.size.width, image1.size.height)]; //Draw 外框 [image2 drawInRect:CGRectMake(0, 0, image2.size.width, image2.size.height)]; UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return resultImage; } #pragma mark 将UIImage变为圆角 + (void) addRoundedRectToPath:(CGContextRef)context rect:(CGRect )rect ovalWidth:(float) ovalWidth ovalHeight:(float) ovalHeight { float fw,fh; if (ovalWidth == 0 || ovalHeight == 0) { CGContextAddRect(context, rect); return; } CGContextSaveGState(context); CGContextTranslateCTM(context, CGRectGetMinX(rect), CGRectGetMinY(rect)); CGContextScaleCTM(context, ovalWidth, ovalHeight); fw = CGRectGetWidth(rect) / ovalWidth; fh = CGRectGetHeight(rect) / ovalHeight; CGContextMoveToPoint(context, fw, fh/2); // Start at lower right corner CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1); // Top right corner CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1); // Top left corner CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1); // Lower left corner CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1); // Back to lower right CGContextClosePath(context); CGContextRestoreGState(context); } + (id) createRoundedRectImage:(UIImage*)image addImage:(UIImage *)addImage size:(CGSize)size{ return [self createRoundedRectImage:image addImage:addImage size:size oval:headOval]; } + (id) createRoundedRectImage:(UIImage*)image addImage:(UIImage *)addImage size:(CGSize)size oval:(CGFloat)oval{ addImage = [self changeImageSize:addImage size:size]; // the size of CGContextRef CGFloat w = size.width * addImage.scale; CGFloat h = size.height * addImage.scale; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, (int)w, (int)h, 8, 4 * (int)w, colorSpace,kCGImageAlphaPremultipliedFirst); CGRect rect = CGRectMake(0, 0, w, h); CGContextBeginPath(context); [self addRoundedRectToPath:context rect:rect ovalWidth:w / oval ovalHeight:h / oval]; CGContextClosePath(context); CGContextClip(context); CGContextDrawImage(context, CGRectMake(0, 0, w, h), image.CGImage); CGImageRef imageMasked = CGBitmapContextCreateImage(context); CGContextRelease(context); CGColorSpaceRelease(colorSpace); return [self addImage:[UIImage imageWithCGImage:imageMasked scale:[UIScreen mainScreen].scale orientation:image.imageOrientation] toImage:addImage]; } + (UIImage *)changeImageSize:(UIImage *)image size:(CGSize)size { UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale); [image drawInRect:CGRectMake(0, 0, size.width, size.height)]; UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return resultImage; } //剪裁&压缩图片 + (UIImage*) scalingAndCroppingToSize:(CGSize)targetSize withImage:(UIImage*)sourceImage { UIImage *newImage = nil; CGSize imageSize = sourceImage.size; CGFloat width = imageSize.width; CGFloat height = imageSize.height; CGFloat targetWidth = targetSize.width; CGFloat targetHeight = targetSize.height; CGFloat scaleFactor = 0.0; CGFloat scaledWidth = targetWidth; CGFloat scaledHeight = targetHeight; //剪裁点的位置,以3*2长方形剪裁为2*2正方形为例,截取image中心部分,剪切点为(0,0.5) CGPoint thumbnailPoint = CGPointMake(0.0,0.0); if (CGSizeEqualToSize(imageSize, targetSize) == NO) { //compress scale CGFloat widthFactor = targetWidth / width; CGFloat heightFactor = targetHeight / height; //set scaleFactoras lesser scale,fit lesser scale if (widthFactor > heightFactor) scaleFactor = widthFactor; // scale to fit height else scaleFactor = heightFactor; // scale to fit width //reset the target size with the new scale factor scaledWidth = width * scaleFactor; scaledHeight = height * scaleFactor; // get cropping point if (widthFactor > heightFactor) { thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; } else if (widthFactor < heightFactor) { thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5; } } UIGraphicsBeginImageContextWithOptions(targetSize, NO, [UIScreen mainScreen].scale); CGRect thumbnailRect = CGRectZero; thumbnailRect.origin = thumbnailPoint; thumbnailRect.size.width = scaledWidth; thumbnailRect.size.height = scaledHeight; //corpping image to special rectangle [sourceImage drawInRect:thumbnailRect]; newImage = UIGraphicsGetImageFromCurrentImageContext(); if(newImage == nil) xLog(@"could not scale image"); //pop the context to get back to the default UIGraphicsEndImageContext(); return newImage; } #pragma 添加阴影 + (void)addShadow:(UIImageView *)imageView image:(UIImage *)image{ imageView.clipsToBounds = NO; //创建对象 CALayer *subLayer = [CALayer layer]; //底色 subLayer.backgroundColor = [UIColor clearColor].CGColor; //阴影大小 subLayer.shadowOffset = CGSizeMake(4, 4); //阴影的深浅 float数值 越小颜色越重 subLayer.shadowRadius = 4.0; //阴影颜色 subLayer.shadowColor = [UIColor darkGrayColor].CGColor; //阴影透明度 subLayer.shadowOpacity = 0.8; //大小 subLayer.frame = CGRectMake(0, 0, CGRectGetWidth(imageView.frame) - 2, CGRectGetHeight(imageView.frame) - 2); //边框颜色 // subLayer.borderColor = [UIColor clearColor].CGColor; //边框宽度 // subLayer.borderWidth = 0; //设置委圆角 subLayer.cornerRadius = CGRectGetWidth(imageView.frame)/2; CALayer *imageLayer = [CALayer layer]; //层的 大小 imageLayer.frame = CGRectMake(0, 0, CGRectGetWidth(imageView.frame) - 2, CGRectGetHeight(imageView.frame) - 2); //设置委圆角 imageLayer.cornerRadius = CGRectGetWidth(imageView.frame)/2; //设置剪辑 imageLayer.masksToBounds = YES; //加载图片 imageLayer.contents = (id)image.CGImage; // 加载 层 [subLayer addSublayer:imageLayer]; [imageView.layer addSublayer:subLayer]; } + (void)addShadow:(UIImageView *)imageView imageName:(NSString *)imageName { } + (NSString *)getWeekDayStr:(NSString *)week{ if (week.length > 0) { NSArray *arr = [self getWeekStr:week removedNil:YES]; if (arr.count == 7) { return @"每天"; }else if (arr.count > 0) { return [arr componentsJoinedByString:@"、"]; } return @"一次"; } return nil; } + (NSMutableArray *)getWeekStr:(NSString *)string removedNil:(BOOL)isRemoved{ NSMutableArray *weekArr = [NSMutableArray arrayWithArray:@[@"",@"",@"",@"",@"",@"",@""]]; [string enumerateSubstringsInRange:NSMakeRange(0, string.length) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) { NSString *str = @""; if ([substring isEqualToString:@"1"]) { switch (substringRange.location) { case 0:str = @"周一";break; case 1:str = @"周二";break; case 2:str = @"周三";break; case 3:str = @"周四";break; case 4:str = @"周五";break; case 5:str = @"周六";break; case 6:str = @"周日";break; default: break; } } [weekArr replaceObjectAtIndex:substringRange.location withObject:str]; }]; if (isRemoved) { [weekArr removeObject:@""]; } return weekArr; } + (NSMutableArray *)getWeekDayDataArr:(NSArray *)arr{ NSMutableArray *weekArr = [NSMutableArray arrayWithArray:@[@"0",@"0",@"0",@"0",@"0",@"0",@"0"]]; [arr enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) { if ([obj isEqualToString:@"周一"]) { [weekArr replaceObjectAtIndex:idx withObject:@"1"]; }else if ([obj isEqualToString:@"周二"]) { [weekArr replaceObjectAtIndex:idx withObject:@"1"]; }else if ([obj isEqualToString:@"周三"]) { [weekArr replaceObjectAtIndex:idx withObject:@"1"]; }else if ([obj isEqualToString:@"周四"]) { [weekArr replaceObjectAtIndex:idx withObject:@"1"]; }else if ([obj isEqualToString:@"周五"]) { [weekArr replaceObjectAtIndex:idx withObject:@"1"]; }else if ([obj isEqualToString:@"周六"]) { [weekArr replaceObjectAtIndex:idx withObject:@"1"]; }else if ([obj isEqualToString:@"周日"]) { [weekArr replaceObjectAtIndex:idx withObject:@"1"]; } }]; return weekArr; } + (UIAlertController *)getAlertWithTitle:(NSString *)title actionTitles:(NSArray *)actionTitles block:(void (^)(UIAlertAction *action))block{ return [myHelper getAlertWithTitle:title actionTitles:actionTitles style:UIAlertControllerStyleActionSheet block:block]; } + (UIAlertController *)getAlertWithTitle:(NSString *)title actionTitles:(NSArray *)actionTitles style:(UIAlertControllerStyle)style block:(void (^)(UIAlertAction *action))block{ UIAlertController *sheet = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:style]; [actionTitles enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) { UIAlertAction *action = [UIAlertAction actionWithTitle:NSLocalizedStringFromTable(obj, @"Localization", @"") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { block(action); }]; [sheet addAction:action]; }]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {}]; [sheet addAction:cancelAction]; return sheet; } + (UIAlertController *)getAlertWithTitle:(NSString *)title message:(NSString *) msg actionTitles:(NSArray *)actionTitles style:(UIAlertControllerStyle)style block:(void (^)(UIAlertAction *action))block{ UIAlertController *sheet = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:style]; NSMutableAttributedString *messageStr = [[NSMutableAttributedString alloc] initWithString:msg]; [messageStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, msg.length)]; [messageStr addAttribute:NSForegroundColorAttributeName value:[UIColor systemGrayColor] range:NSMakeRange(0, msg.length)]; [sheet setValue:messageStr forKey:@"attributedMessage"]; [actionTitles enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) { UIAlertAction *action = [UIAlertAction actionWithTitle:NSLocalizedStringFromTable(obj, @"Localization", @"") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { block(action); }]; [sheet addAction:action]; }]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { block(action); }]; [sheet addAction:cancelAction]; return sheet; } + (UIAlertController *)getAlertWithPicture:(void (^)(UIImagePickerController *imagePickerVC))block{ if([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo] == AVAuthorizationStatusDenied){ // [UICommon MessageErrorText:NSLocalizedStringFromTable(@"请在iOS设备的 设置-隐私-相机 中允许访问相机。", @"Localization", @"")]; LGAlertView *alertView = [[LGAlertView alloc] initWithTitle:[NSString stringWithFormat:@"请为%@打开相机权限",APPName] message:@"" style:LGAlertViewStyleAlert buttonTitles:@[@"设置"] cancelButtonTitle:@"取消" destructiveButtonTitle:nil actionHandler:^(LGAlertView *alertView, NSString *title, NSUInteger index) { NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString]; if([[UIApplication sharedApplication] canOpenURL:url]) { NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];           [[UIApplication sharedApplication] openURL:url]; } } cancelHandler:nil destructiveHandler:nil]; [alertView showAnimated:YES completionHandler:nil]; }else if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusDenied){ // [UICommon MessageErrorText:NSLocalizedStringFromTable(@"请在iOS设备的 设置-隐私-照片 中允许访问照片。", @"Localization", @"")]; LGAlertView *alertView = [[LGAlertView alloc] initWithTitle:[NSString stringWithFormat:@"请为%@打开相机权限",APPName] message:@"" style:LGAlertViewStyleAlert buttonTitles:@[@"设置"] cancelButtonTitle:@"取消" destructiveButtonTitle:nil actionHandler:^(LGAlertView *alertView, NSString *title, NSUInteger index) { NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString]; if([[UIApplication sharedApplication] canOpenURL:url]) { NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];           [[UIApplication sharedApplication] openURL:url]; } } cancelHandler:nil destructiveHandler:nil]; [alertView showAnimated:YES completionHandler:nil]; }else{ UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init]; imagePickerController.allowsEditing = YES; UIAlertController *sheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet]; UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:NSLocalizedStringFromTable(@"拍照", @"Localization", @"") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera; block(imagePickerController); }]; UIAlertAction *libraryAction = [UIAlertAction actionWithTitle:NSLocalizedStringFromTable(@"从相册选择", @"Localization", @"") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { block(imagePickerController); }]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {}]; [sheet addAction:cameraAction]; [sheet addAction:libraryAction]; [sheet addAction:cancelAction]; return sheet; } return nil; } + (NSMutableString *)secToStr:(NSInteger)sec{ NSMutableString *timeStr = [NSMutableString string]; NSInteger day = sec / (60 * 60 * 24); sec -= day * 60 * 60 * 24; NSInteger ousr = sec / (60 * 60); sec -= ousr * 60 * 60; NSInteger minutes = sec / 60; sec -= minutes * 60; if (day > 0) { [timeStr appendString:[NSString stringWithFormat:@"%zi天",day]]; } if (ousr > 0) { [timeStr appendString:[NSString stringWithFormat:@"%zi小时",ousr]]; } if (day > 0) { [timeStr appendString:[NSString stringWithFormat:@"%zi分",minutes]]; return timeStr; } if (sec < 10) { [timeStr appendString:[NSString stringWithFormat:@"%zi分0%zi秒",minutes,sec]]; }else{ [timeStr appendString:[NSString stringWithFormat:@"%zi分%zi秒",minutes,sec]]; } return timeStr; } + (NSString *)distanceTimeWithBeforeTime:(double)beTime { NSTimeInterval now = [[NSDate date]timeIntervalSince1970]; double distanceTime = now - beTime; NSString * distanceStr; NSDate * beDate = [NSDate dateWithTimeIntervalSince1970:beTime]; NSDateFormatter *df2 = [[NSDateFormatter alloc]init]; [df2 setDateFormat:@"yyyy-MM-dd HH:mm"]; distanceStr = [df2 stringFromDate:beDate]; return distanceStr; // NSDateFormatter * df = [[NSDateFormatter alloc]init]; // [df setDateFormat:@"HH:mm"]; // NSString * timeStr = [df stringFromDate:beDate]; // // [df setDateFormat:@"dd"]; // NSString * nowDay = [df stringFromDate:[NSDate date]]; // NSString * lastDay = [df stringFromDate:beDate]; // // if (distanceTime < 60) {//小于一分钟 // distanceStr = @"刚刚"; // } // else if (distanceTime <60*60) {//时间小于一个小时 // distanceStr = [NSString stringWithFormat:@"%ld分钟前",(long)distanceTime/60]; // } // else if(distanceTime <24*60*60 && [nowDay integerValue] == [lastDay integerValue]){//时间小于一天 // distanceStr = [NSString stringWithFormat:@"今天 %@",timeStr]; // } // else if(distanceTime<24*60*60*2 && [nowDay integerValue] != [lastDay integerValue]){ // // if ([nowDay integerValue] - [lastDay integerValue] ==1 || ([lastDay integerValue] - [nowDay integerValue] > 10 && [nowDay integerValue] == 1)) { // distanceStr = [NSString stringWithFormat:@"昨天 %@",timeStr]; // } // else{ // [df setDateFormat:@"MM-dd HH:mm"]; // distanceStr = [df stringFromDate:beDate]; // } // // } // else if(distanceTime <24*60*60*365){ // [df setDateFormat:@"MM-dd HH:mm"]; // distanceStr = [df stringFromDate:beDate]; // } // else{ // [df setDateFormat:@"yyyy-MM-dd HH:mm"]; // distanceStr = [df stringFromDate:beDate]; // } // return distanceStr; } + (void)setBtnUpImageDownTitle:(UIButton *)btn{ CGSize btnSize = btn.bounds.size; UIImage *image = btn.imageView.image; NSString *title = btn.titleLabel.text; CGSize titleSize = [title boundingRectWithSize:CGSizeMake(MAXFLOAT, btn.titleLabel.frame.size.height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:btn.titleLabel.font} context:nil].size; btn.titleEdgeInsets = UIEdgeInsetsMake(image.size.height, -image.size.width, 0, 0); if ([CurrentSystemVersion doubleValue] >= 13.0) { btn.imageEdgeInsets = UIEdgeInsetsMake(-titleSize.height, btnSize.width / 2 - image.size.width/2 , 0.5*titleSize.height, 0); }else{ btn.imageEdgeInsets = UIEdgeInsetsMake(-titleSize.height, image.size.width/2 , 0.5*titleSize.height, 0); } } /** 获取当前改账号的登录类型 @return 1 手机号登录 2 微信号登录 3 imei号登录 (体验客) */ + (int)getNowAccoutType:(User*)user{ int type = 0; if(user.loginName != nil){ if(user.account_status.intValue == 1){ // 手机账号 type = 1; }else{ //imei 登录的 type = 3; } }else{ //微信的 type = 2; } return type; } + (UIColor *)colorAtPixel:(CGPoint)point{ UIImage *image = [self fullScreenshots]; if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, image.size.width, image.size.height), point)) { return nil; } NSInteger pointX = trunc(point.x); NSInteger pointY = trunc(point.y); CGImageRef cgImage = image.CGImage; NSUInteger width = image.size.width; NSUInteger height = image.size.height; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); int bytesPerPixel = 4; int bytesPerRow = bytesPerPixel * 1; NSUInteger bitsPerComponent = 8; unsigned char pixelData[4] = { 0, 0, 0, 0 }; CGContextRef context = CGBitmapContextCreate(pixelData, 1, 1, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); CGColorSpaceRelease(colorSpace); CGContextSetBlendMode(context, kCGBlendModeCopy); CGContextTranslateCTM(context, -pointX, pointY-(CGFloat)height); CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height), cgImage); CGContextRelease(context); CGFloat red = (CGFloat)pixelData[0] / 255.0f; CGFloat green = (CGFloat)pixelData[1] / 255.0f; CGFloat blue = (CGFloat)pixelData[2] / 255.0f; CGFloat alpha = (CGFloat)pixelData[3] / 255.0f; return [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; } + (UIImage *)fullScreenshots{ UIWindow *screenWindow = [[UIApplication sharedApplication] keyWindow]; UIGraphicsBeginImageContext(screenWindow.frame.size);//全屏截图,包括window [screenWindow.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); return viewImage; } /** 获取 关系名字数组 */ +(NSArray *)getRelationshipNameArr:(NSInteger)deviceType { if (deviceType == 3) return @[@"家人",@"朋友",@"自定义"]; else return @[@"爸爸", @"妈妈", @"爷爷", @"奶奶", @"外公", @"外婆", @"叔叔", @"阿姨", @"自定义"]; } /** 获取 关系未选中的图片数组 */ +(NSArray *)getUnclickRelationshipImageArr:(NSInteger)deviceType{ // if (deviceType == 3) // return @[@"icon_unclick_father_head_portrait", // @"icon_unclick_uncle_head_portrait", // @"icon_unclick_relative_head_portrait"]; // else // return @[@"icon_unclick_father_head_portrait", // @"icon_unclick_mother_head_portrait", // @"icon_unclick_yy_head_portrait", // @"icon_unclick_nn_head_portrait", // @"icon_unclick_waigong_head_portrait", // @"icon_unclick_waipo_head_portrait", // @"icon_unclick_uncle_head_portrait", // @"icon_unclick_aunt_head_portrait", // @"icon_unclick_relative_head_portrait"]; if (deviceType == 3) return @[@"icon_click_father_head_portrait", @"icon_click_uncle_head_portrait", @"icon_click_relative_head_portrait"]; else return @[@"icon_click_father_head_portrait", @"icon_click_mother_head_portrait", @"icon_click_yy_head_portrait", @"icon_click_nn_head_portrait", @"icon_click_waigong_head_portrait", @"icon_click_waipo_head_portrait", @"icon_click_uncle_head_portrait", @"icon_click_aunt_head_portrait", @"icon_click_relative_head_portrait"]; } /** 获取 关系选中的图片数组 */ +(NSArray *)getClickRelationshipImageArr:(NSInteger)deviceType{ if (deviceType == 3) return @[@"icon_click_father_head_portrait", @"icon_click_uncle_head_portrait", @"icon_click_relative_head_portrait"]; else return @[@"icon_click_father_head_portrait", @"icon_click_mother_head_portrait", @"icon_click_yy_head_portrait", @"icon_click_nn_head_portrait", @"icon_click_waigong_head_portrait", @"icon_click_waipo_head_portrait", @"icon_click_uncle_head_portrait", @"icon_click_aunt_head_portrait", @"icon_click_relative_head_portrait"]; } /** 根据 关系id 获取 关系名字 */ +(NSString *)getRelationshipNameWithCodeID:(int)code deviceType:(NSInteger)deviceType{ if (code != 9) { return [self getRelationshipNameArr:deviceType][code-1]; }else{ return [self getRelationshipNameArr:deviceType].lastObject; } } /** 根据 关系id 获取 关系未选中的图片 */ +(UIImage *)getUnclickRelationshipImageWithCodeID:(int)code deviceType:(NSInteger)deviceType{ if (code != 9) { return [UIImage imageNamed:[self getUnclickRelationshipImageArr:deviceType][code-1]]; }else{ return [UIImage imageNamed:[self getUnclickRelationshipImageArr:deviceType].lastObject]; } } /** 根据 关系id 获取 关系选中的图片 */ +(UIImage *)getClickRelationshipImageWithCodeID:(int)code deviceType:(NSInteger)deviceType{ if (code != 9) { return [UIImage imageNamed:[self getClickRelationshipImageArr:deviceType][code-1]]; }else{ return [UIImage imageNamed:[self getClickRelationshipImageArr:deviceType].lastObject]; } } #pragma mark 获取文本宽度 + (CGFloat)getWidthWithText:(NSString *)text withFont:(UIFont *)font { CGSize size = [text sizeWithAttributes:@{NSFontAttributeName:font}]; return size.width; } @end