iOS 截屏,截取长图,图片拼接

作者: Jixin | 来源:发表于2016-08-08 18:37 被阅读2823次

1.截取制定范围(非长图)

- (UIImage *)screenShotWithSize(CGSize *)size {
    UIImage* image = nil;
    /*
     *UIGraphicsBeginImageContextWithOptions有三个参数
     *size    bitmap上下文的大小,就是生成图片的size
     *opaque  是否不透明,当指定为YES的时候图片的质量会比较好
     *scale   缩放比例,指定为0.0表示使用手机主屏幕的缩放比例
     */
    UIGraphicsBeginImageContextWithOptions(size, YES, 0.0);
    //此处我截取的是TableView的header.
    [self.tableHeaderView.layer renderInContext: UIGraphicsGetCurrentContext()];
    image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();
    if (image != nil) {
        return image;
    }else {
        return nil;
    }
}

2.截取长图,如TableView,CollectionView

- (UIImage *)screenShot {
    UIImage* image = nil;
    UIGraphicsBeginImageContextWithOptions(self.collectionView.contentSize, YES, 0.0);

    //保存collectionView当前的偏移量
    CGPoint savedContentOffset = self.collectionView.contentOffset;
    CGRect saveFrame = self.collectionView.frame;

    //将collectionView的偏移量设置为(0,0)
    self.collectionView.contentOffset = CGPointZero;
    self.collectionView.frame = CGRectMake(0, 0, self.collectionView.contentSize.width, self.collectionView.contentSize.height);

    //在当前上下文中渲染出collectionView
    [self.collectionView.layer renderInContext: UIGraphicsGetCurrentContext()];
    //截取当前上下文生成Image
    image = UIGraphicsGetImageFromCurrentImageContext();

    //恢复collectionView的偏移量
    self.collectionView.contentOffset = savedContentOffset;
    self.collectionView.frame = saveFrame;

    UIGraphicsEndImageContext();

    if (image != nil) {
        return image;
    }else {
        return nil;
    }
}

3.图片拼接

将两张图片拼接在一起,第二张图片拼接在第一张图的下面。

/*masterImage  主图片,生成的图片的宽度为masterImage的宽度
 *slaveImage   从图片,拼接在masterImage的下面
 */
- (UIImage *)addSlaveImage:(UIImage *)slaveImage toMasterImage:(UIImage *)masterImage {
    CGSize size;
    size.width = masterImage.size.width;
    size.height = masterImage.size.height + slaveImage.size.height;
    
    UIGraphicsBeginImageContextWithOptions(size, YES, 0.0);
    
    //Draw masterImage
    [masterImage drawInRect:CGRectMake(0, 0, masterImage.size.width, masterImage.size.height)];
    
    //Draw slaveImage
    [slaveImage drawInRect:CGRectMake(0, masterImage.size.height, masterImage.size.width, slaveImage.size.height)];
    
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    return resultImage;
}

相关文章

网友评论

  • BeethOven:这种三个操作下来 虽然第三个操作依赖一二个,也不需要进行线程处理吗,都是必须在主线程吗
  • 心语风尚:截取长图 如tableview 有20个cell 截图只有前面12个cell 没有全部截取出来
    LD_左岸:这个您解决了吗 我这也有这个问题
  • 哦_我不知道:博主你好,这种截图拼接应该会有一定的尺寸限制,如果图片非常长,全部在内存里拼接就会被系统杀掉,不知道博主有没有碰到这种问题
    哦_我不知道:@心语风尚 没发现呢,现在想到的就是当达到一定限制时就再创建一张新的,保存之前的图片。
    心语风尚:@lawson_y 解决
    心语风尚:@lawson_y 有办法吗

本文标题:iOS 截屏,截取长图,图片拼接

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