iOS开发资料收集

iOS UIView延展:指定区域截图

2016-10-06  本文已影响180人  FogeeY

- (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];
上一篇下一篇

猜你喜欢

热点阅读