美文网首页
iOS 对UIView截图的一些事

iOS 对UIView截图的一些事

作者: no1ever | 来源:发表于2020-11-20 16:28 被阅读0次

常用的对UIView的基本截图方法:

- (UIImage *)snapshotSingleView:(UIView *)view {
#pragma mark -注意⚠️这里
//UIGraphicsBeginImageContextWithOptions 第3个参数0(无缩放, 无损截图), 1(1倍缩放)
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
//    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

使用上面方法截图后,如果保存到沙盒:

//下面测试3种保存方式
[UIImageJPEGRepresentation(image, 1) writeToFile:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/1.jpg"] atomically:YES];
[UIImageJPEGRepresentation(image, 0.6) writeToFile:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/2.jpg"] atomically:YES];
[UIImagePNGRepresentation(image) writeToFile:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/3.png"] atomically:YES];

你可能会发现图片的尺寸变大了,比如是你在Xcode控制台看到的大小的2倍(iPhone7)或者3倍(iPhone7 Plus)。原因猜测是和逻辑像素缩放有关

[UIScreen mainScreen].scale

下面提供个修改图片大小的方法(会变模糊),我们可以用来对图片缩放或者固定尺寸:

//修改图片的分辨率
- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

最后列举一个特殊的应用场景,比如你截图之后,又想分割图片。
比如,UIView 的Frame是 (300, 300) , 按照前面描述的情况无损截图后的图片 UIImage 实际大小就是 (600, 600) 或者 (900, 900) 。如果此时你想在 UIImage 上切割一个相对于UIView位置为 A:(100, 100, 50, 50) 的小图,怎么办呢?

方法一:

修改 UIImage 的大小为 (300, 300) ,然后再取 坐标点的图。

- (UIImage *)captureOriginalImage:(UIImage *)oImage frame:(CGRect)fra {
  GImageRef ref = CGImageCreateWithImageInRect(oImage.CGImage, fra);
    UIImage *i = [UIImage imageWithCGImage:ref];
    CGImageRelease(ref);
    return i;
}

这个方法有个弊端,就是会导致图片模糊。

方法二:

利用 [UIScreen mainScreen].scale 重新计算出相对于 UIImage 的切割位置。这种方式就可以实现无损切割了

- (UIImage *)captureOriginalImage:(UIImage *)oImage frame:(CGRect)fra {

#pragma mark -注意⚠️这里
    CGFloat scale = [UIScreen mainScreen].scale;
    CGRect nFra = CGRectMake(fra.origin.x * scale, fra.origin.y * scale, fra.size.width * scale, fra.size.height * scale);
    
    CGImageRef ref = CGImageCreateWithImageInRect(oImage.CGImage, nFra);
    UIImage *i = [UIImage imageWithCGImage:ref];
    CGImageRelease(ref);

    return i;
}

⚠️ 以上讨论的是对iOS设备屏幕截图后导致的一些问题,如果不是截图生成的图,则不用考虑缩放。
传送门


⚽️ 👍+🧧

相关文章

网友评论

      本文标题:iOS 对UIView截图的一些事

      本文链接:https://www.haomeiwen.com/subject/xxodiktx.html