屏幕截图,图片的底部为啥有白线?并且自己的屏幕图片明明切图了,但是为啥截的图还是有会没有切圆角的那部分?what?why?
demo在这里
问题一:为啥屏幕截图底部会有白线?
1.可能会出现白线的代码如下:
//对某个view进行截图
-(UIImage *)screenshotsImageFromView:(UIView *)view {
JCShowView *showView = (JCShowView *)view;
CGRect screenRect = [showView bounds];
NSInteger scale = 1;
if ([[UIScreen mainScreen]respondsToSelector:@selector(scale)]) {
CGFloat tmp = [[UIScreen mainScreen]scale];
if (tmp > 1.5) {
scale = 2.0;
}
if (tmp > 2.5) {
scale=3.0;
}
}
if (scale > 1.5) {
UIGraphicsBeginImageContextWithOptions(screenRect.size, NO, scale);
} else {
UIGraphicsBeginImageContext(screenRect.size);
}
CGContextRef ctx = UIGraphicsGetCurrentContext();
[showView.layer renderInContext:ctx];
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
2.常规测试了也没发现啥问题,最后查阅资料问题出在这行代码了
UIGraphicsBeginImageContextWithOptions(screenRect.size, NO, scale);
原因是因为当屏幕的高度是
CGFloat
类型的时候会出现白线,所以把高度通过NSNumber
转成NSInteger
好了、优化后代码如下:
NSInteger screenH = [[NSNumber numberWithDouble:screenRect.size.height] integerValue];
UIGraphicsBeginImageContextWithOptions(CGSizeMake(screenRect.size.width, screenH), NO, scale)
问题一:为啥屏幕截图上的图片圆角已经切了,为啥最后相册查看的时候还是显示没切掉的圆角呢?
有问题的图如下:
Snip20200224_2.png
分析:圆角应该在图片上切,而图片的父视图的背景应该在截屏的一瞬间做下处理。优化后在截图正常了。如下图:
CGContextRef ctx = UIGraphicsGetCurrentContext();
#截取的时候先修改成黑色背景
showView.backgroundColor = [UIColor blackColor];
[showView.layer renderInContext:ctx];
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
#完毕之后在修改成白色背景
showView.backgroundColor = [UIColor whiteColor];

最终代码如下:
-(UIImage *)screenshotsImageFromView:(UIView *)view {
JCShowView *showView = (JCShowView *)view;
CGRect screenRect = [showView bounds];
NSInteger scale = 1;
if ([[UIScreen mainScreen]respondsToSelector:@selector(scale)]) {
CGFloat tmp = [[UIScreen mainScreen]scale];
if (tmp > 1.5) {
scale = 2.0;
}
if (tmp > 2.5) {
scale=3.0;
}
}
if (scale > 1.5) {
// UIGraphicsBeginImageContextWithOptions(screenRect.size, NO, scale);
//这里的屏幕高度需要设置成NSInteger类型的否则截图底部会有白线
NSInteger screenH = [[NSNumber numberWithDouble:screenRect.size.height] integerValue];
UIGraphicsBeginImageContextWithOptions(CGSizeMake(screenRect.size.width, screenH), NO, scale);
} else {
UIGraphicsBeginImageContext(screenRect.size);
}
CGContextRef ctx = UIGraphicsGetCurrentContext();
showView.backgroundColor = [UIColor blackColor];
[showView.layer renderInContext:ctx];
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
showView.backgroundColor = [UIColor whiteColor];
return image;
}
网友评论