美文网首页iOS开发资料收集
iOS UIView延展:指定区域截图

iOS UIView延展:指定区域截图

作者: FogeeY | 来源:发表于2016-10-06 15:36 被阅读180次

- (UIImage *)screenshotWithRect:(CGRect)rect
{
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);

    CGContextRef context = UIGraphicsGetCurrentContext();

    if (context == NULL)
    {
        return nil;
    }
    CGContextSaveGState(context);
    CGContextTranslateCTM(context, -rect.origin.x, -rect.origin.y);
    [self snapshotViewAfterScreenUpdates:YES];
    if( [self respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
    {
        [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:NO];
    }else
    {
         [self.layer renderInContext:context];
    }

    CGContextRestoreGState(context);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;
}

注意:[self snapshotViewAfterScreenUpdates:YES];

参数:YES-代表视图的属性改变渲染完毕后截屏,NO-代表立刻将当前状态的视图截图

图片转格式
//    NSData *imageData = UIImageJPEGRepresentation(image, 1); // convert to jpeg

//    image = [UIImage imageWithData:imageData scale:[UIScreen mainScreen].scale];

相关文章

网友评论

  • _Sven:非常感谢!项目中需要将view形变缩放之后的图片拿出来渲染,但是总是拿不到形变后的图片,[self snapshotViewAfterScreenUpdates:YES]; 这个帮了我大忙!感激不尽!

本文标题:iOS UIView延展:指定区域截图

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