【Coding】【2】iOS常用代码(二)

本文最后更新于:2021年12月22日 上午

【Coding】系列目录


目录

1. 图片拉伸

2. 获取App基本信息

3. 获取渐变颜色图片

4. 图片合成文字

5. 合成图片

6. 旋转图片

7. 获取当前屏幕最顶层的ViewController

8. OC自定义Log


内容

1. 图片拉伸

1
2
/// 拉伸leftCapWidth右边,topCapHeight下边1个像素的位置,其余地方不动
- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight;

2. 获取App基本信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/// 1. 获取设备名称
NSString *deviceName = [[UIDevice currentDevice] name];

/// 2. 获取系统版本号
NSString *sysVersion = [[UIDevice currentDevice] systemVersion];

/// 3. 获取设备唯一标识符
NSString *deviceUUID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];

/// 4. 获取设备的型号
NSString *deviceModel = [[UIDevice currentDevice] model];

NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
// 5. 获取App的版本号
NSString *appVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
// 6. 获取App的build版本
NSString *appBuildVersion = [infoDic objectForKey:@"CFBundleVersion"];
// 7. 获取App的名称
NSString *appName = [infoDic objectForKey:@"CFBundleDisplayName"];

3. 获取渐变颜色图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
+ (UIImage *)gradientImageWithColors:(NSArray *)colors rect:(CGRect)rect {
if (!colors.count || CGRectEqualToRect(rect, CGRectZero)) {
return nil;
}

CAGradientLayer *gradientLayer = [CAGradientLayer layer];

gradientLayer.frame = rect;
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint = CGPointMake(1, 0);
NSMutableArray *mutColors = [NSMutableArray arrayWithCapacity:colors.count];
for (UIColor *color in colors) {
[mutColors addObject:(__bridge id)color.CGColor];
}
gradientLayer.colors = mutColors;

UIGraphicsBeginImageContextWithOptions(gradientLayer.frame.size, gradientLayer.opaque, 0);
[gradientLayer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

NSString * path = NSHomeDirectory();
NSString * imgPath =[path stringByAppendingString:@"/Documents/222.png"];
NSLog(@"imgPath %@",imgPath);
[UIImagePNGRepresentation(outputImage) writeToFile:imgPath atomically:YES];
return outputImage;
}

4. 图片合成文字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/// 图片合成文字
/// @param text 文字
/// @param fontSize 大小
/// @param textColor 颜色
/// @param textFrame 文字位置
/// @param image 原始图片
/// @param viewFrame 图片所在view的位置
+ (UIImage *)imageWithText:(NSString *)text
textFont:(NSInteger)fontSize
textColor:(UIColor *)textColor
textFrame:(CGRect)textFrame
originImage:(UIImage *)image
imageLocationViewFrame:(CGRect)viewFrame {

if (!text) { return image; }
if (!fontSize) { fontSize = 17; }
if (!textColor) { textColor = [UIColor blackColor]; }
if (!image) { return nil; }
if (viewFrame.size.height==0 || viewFrame.size.width==0 || textFrame.size.width==0 || textFrame.size.height==0 ){return nil;}

NSString *mark = text;
CGFloat height = [mark sizeWithPreferWidth:textFrame.size.width font:[UIFont systemFontOfSize:fontSize]].height; // 此分类方法要导入头文件
if ((height + textFrame.origin.y) > viewFrame.size.height) { // 文字高度超出父视图的宽度
height = viewFrame.size.height - textFrame.origin.y;
}

UIGraphicsBeginImageContext(viewFrame.size);
[image drawInRect:CGRectMake(0, 0, viewFrame.size.width, viewFrame.size.height)];
NSDictionary *attr = @{NSFontAttributeName: [UIFont systemFontOfSize:fontSize], NSForegroundColorAttributeName : textColor };
//位置显示
[mark drawInRect:CGRectMake(textFrame.origin.x, textFrame.origin.y, textFrame.size.width, height) withAttributes:attr];

UIImage *aimg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return aimg;
}

5. 合成图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/// 合成后的图片 (以坐标为参考点,不准确)
/// @param imageArray 图片数组 第一张图片位画布,所以最大
/// @param frameArray 坐标数组
+ (UIImage *)composeImageWithArray:(NSArray<UIImage *> *)imageArray frameArray:(NSArray *)frameArray {
if (imageArray.count == 0) { return nil; }
if (imageArray.count == 1) { return imageArray.firstObject; }
if (imageArray.count != frameArray.count) { return nil; }

__block UIImage *image0;
[imageArray enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if (obj.size.width == 0) {
*stop = YES;
image0 = idx == 0 ? obj : [imageArray objectAtIndex:idx - 1];
}
}];
if (image0) {
return image0;
}

NSMutableArray *arrayImages = imageArray.mutableCopy;
NSMutableArray *arrayFrames = frameArray.mutableCopy;

NSString *string = arrayFrames.firstObject;
CGRect fristRect = CGRectFromString(string);
UIImage *img0 = arrayImages.firstObject;
CGFloat w0 = fristRect.size.width;
CGFloat h0 = fristRect.size.height;
// 以第一张的图大小为画布创建上下文
UIGraphicsBeginImageContext(CGSizeMake(w0, h0));
[img0 drawInRect:CGRectMake(0, 0, w0, h0)];// 先把第一张图片 画到上下文中


for (int i = 1; i < arrayImages.count; i ++) {
NSString *string2 = [arrayFrames objectAtIndex:i];
CGRect secondRect = CGRectFromString(string2);
UIImage *img1 = [arrayImages objectAtIndex:1];
[img1 drawInRect:secondRect];// 再把小图放在上下文中
}

UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext();// 从当前上下文中获得最终图片
UIGraphicsEndImageContext();// 关闭上下文
return resultImg;
}

/// 合成后的图片 (以坐标为参考点,准确)
/// @param mainImage 第一张图片位画布
/// @param viewFrame 第一张图片所在View的frame(获取压缩比用)
/// @param imgArray 子图片数组
/// @param frameArray 子图片坐标数组
+ (UIImage *)composeImageOnMainImage:(UIImage * _Nonnull)mainImage
mainImageViewFrame:(CGRect)viewFrame
subImageArray:(NSArray * _Nonnull)imgArray
subImageFrameArray:(NSArray * _Nonnull)frameArray {
if (!mainImage) { return nil; }
if (viewFrame.size.width == 0 || viewFrame.size.height == 0) { return nil; }
if (imgArray.count == 0) { return nil; }
if (imgArray.count == 1) { return imgArray.firstObject; }
if (imgArray.count != frameArray.count) { return nil; }

// 此处拿到缩放比例
CGFloat widthScale = mainImage.size.width / viewFrame.size.width;
CGFloat heightScale = mainImage.size.height / viewFrame.size.height;

UIGraphicsBeginImageContext(CGSizeMake(mainImage.size.width, mainImage.size.height));
[mainImage drawInRect:CGRectMake(0, 0, mainImage.size.width, mainImage.size.height)];
int i = 0;
for (UIImage *img in imgArray) {
NSString *string = [frameArray objectAtIndex:i];
CGRect fristRect = CGRectFromString(string);
[img drawInRect:CGRectMake(fristRect.origin.x * widthScale, fristRect.origin.y * heightScale, fristRect.size.width, fristRect.size.height)];
i+=1;
}

UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return resultImg == nil ? mainImage : resultImg;
}

6. 旋转图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
+ (UIImage *)image:(UIImage *)image rotation:(UIImageOrientation)orientation
{
long double rotate = 0.0;
CGRect rect;
float translateX = 0;
float translateY = 0;
float scaleX = 1.0;
float scaleY = 1.0;

switch (orientation) {
case UIImageOrientationLeft:
rotate = M_PI_2;
rect = CGRectMake(0, 0, image.size.height, image.size.width);
translateX = 0;
translateY = -rect.size.width;
scaleY = rect.size.width/rect.size.height;
scaleX = rect.size.height/rect.size.width;
break;
case UIImageOrientationRight:
rotate = 33 * M_PI_2;
rect = CGRectMake(0, 0, image.size.height, image.size.width);
translateX = -rect.size.height;
translateY = 0;
scaleY = rect.size.width/rect.size.height;
scaleX = rect.size.height/rect.size.width;
break;
case UIImageOrientationDown:
rotate = M_PI;
rect = CGRectMake(0, 0, image.size.width, image.size.height);
translateX = -rect.size.width;
translateY = -rect.size.height;
break;
default:
rotate = 0.0;
rect = CGRectMake(0, 0, image.size.width, image.size.height);
translateX = 0;
translateY = 0;
break;
}

UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
//做CTM变换
CGContextTranslateCTM(context, 0.0, rect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextRotateCTM(context, rotate);
CGContextTranslateCTM(context, translateX, translateY);

CGContextScaleCTM(context, scaleX, scaleY);
//绘制图片
CGContextDrawImage(context, CGRectMake(0, 0, rect.size.width, rect.size.height), image.CGImage);

UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();

return newPic;
}

7. 获取当前屏幕最顶层的ViewController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// UIViewController+TopViewController.h

+ (UIViewController * )topViewController {
UIViewController *resultVC;
resultVC = [self recursiveTopViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
while (resultVC.presentedViewController) {
resultVC = [self recursiveTopViewController:resultVC.presentedViewController];
}
return resultVC;
}

+ (UIViewController * )recursiveTopViewController:(UIViewController *)vc {
if ([vc isKindOfClass:[UINavigationController class]]) {
return [self recursiveTopViewController:[(UINavigationController *)vc topViewController]];
} else if ([vc isKindOfClass:[UITabBarController class]]) {
return [self recursiveTopViewController:[(UITabBarController *)vc selectedViewController]];
} else {
return vc;
}
return nil;
}

使用

1
UIViewController *vc = [UIViewController toViewController];

8. OC自定义Log

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 只打印
static int BYLogLevelSilent = 1;
// 简单打印
static int BYLogLevelSimple = 2;
// 冗长打印
static int BYLogLevelVerbose = 3;
//自定义Log级别
#define BYLogLevel BYLogLevelSilent

#ifdef DEBUG
#define BYLog(FORMAT, ...) {\
if(BYLogLevel == BYLogLevelSilent){\
fprintf(stderr, "Log: %s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);\
} else if(BYLogLevel == BYLogLevelSimple){\
fprintf(stderr, "Log: File=> %s Message=> %s\n", [[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);\
} else {\
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];\
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];\
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];\
[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss:SSS"]; \
NSString *time = [dateFormatter stringFromDate:[NSDate date]];\
fprintf(stderr,"\n============>\nTime: %s\nFile: %s\nLine: %d\nMessage: %s\n<============\n",[time UTF8String], [[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__, [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);\
}\
}

#else
#define BYLog(FORMAT, ...) nil;
#endif

联系方式

邮箱: adrenine@163.com