美文网首页
ios view转图片

ios view转图片

作者: tongyuling | 来源:发表于2022-09-06 15:39 被阅读0次

    方法一:View的大小不大于手机屏幕
    #pragma mark - 方法一:View的大小不大于手机屏幕
    - (UIImage *)GetmakeImageWithView:(UIView *)view andWithSize:(CGSize)size
    {
        // 下面方法,第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果,需要传NO,否则传YES。第三个参数就是屏幕密度了,关键就是第三个参数 [UIScreen mainScreen].scale。
        UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
        [view.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image;
    }
    

    方法二:View的大小大于手机屏幕
    #pragma mark - 方法二:View的大小大于手机屏幕
    - (UIImage *) snapshotWithScrollView:(UIScrollView *)scrollView
    {
        UIImage * image = nil;
        UIGraphicsBeginImageContext(scrollView.contentSize);
        
        CGPoint savedContentOffset = scrollView.contentOffset;
        CGRect savedFrame = scrollView.frame;
        scrollView.contentOffset = CGPointZero;
        scrollView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height);
        [scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
        image = UIGraphicsGetImageFromCurrentImageContext();
        scrollView.contentOffset = savedContentOffset;
        scrollView.frame = savedFrame;
        
        UIGraphicsEndImageContext();
        if (image != nil) {
            return image;
        }
        return nil;
    }
    

    截取view中某个区域生成一张图片
    #pragma mark - 截取view中某个区域生成一张图片
    - (UIImage *)shotWithView:(UIView *)view scope:(CGRect)scope
    {
        CGImageRef imageRef = CGImageCreateWithImageInRect([self GetmakeImageWithView:view andWithSize:view.bounds.size].CGImage, scope);
        UIGraphicsBeginImageContext(scope.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGRect rect = CGRectMake(0, 0, scope.size.width, scope.size.height);
        CGContextTranslateCTM(context, 0, rect.size.height);//下移
        CGContextScaleCTM(context, 1.0f, -1.0f);//上翻
        CGContextDrawImage(context, rect, imageRef);
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        CGImageRelease(imageRef);
        return image;
    }
    

    相关文章

      网友评论

          本文标题:ios view转图片

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