Swift/iOS - 截屏,长屏,拼图,保存图片到指定的相册

注意

在iOS中访问相册,首先我们得获取用户授权,在iOS10之前不用再Info.plist写参数。
在iOS10 之后要自定义弹出的信息

Privacy - Photo Library Usage Description
Privacy - Camera Usage Description

获取权限

    /// 获取权限
    ///
    /// - Parameter accessBlock:  闭包回调
    func accessCameraAuthority(accessBlock:AccessBlock!)
    {
        let authStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
        if authStatus == AVAuthorizationStatus.notDetermined {
            // 请求授权
            AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeAudio, completionHandler: { finish in
                if finish {
                    if (accessBlock) != nil
                    {
                        accessBlock(true)
                    }
                }
                else
                {
                    if (accessBlock) != nil
                    {
                        accessBlock(false)
                    }
                }
            })
        }
        else if authStatus == AVAuthorizationStatus.authorized
        {
            // 授权成功
            if (accessBlock) != nil
            {
                accessBlock(true)
            }
        }
        else
        {
            // 用户拒绝授权
            if (accessBlock) != nil
            {
                accessBlock(false)
            }
        }
    }

当返回true,我们就可以有访问权限了。
在iOS中截屏的方法如下:

    /// 截屏
    ///
    /// - Parameters:
    ///   - view: 要截屏的view
    /// - Returns: 一个UIImage
    func cutImageWithView(view:UIView) -> UIImage
    {
        // 参数①:截屏区域  参数②:是否透明  参数③:清晰度
        UIGraphicsBeginImageContextWithOptions(view.frame.size, true, UIScreen.main.scale)
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext();
        return image;
    }

这个方法是获取当前view的内容,size的大小要巧妙的设置,比如你的view超出了看到的屏幕,你使用截图下来,
就是一部分回事黑色的区域。你截取当前能看到的,就widow就可以了。
我们在使用很多APP的时候会截出很长的图,这个时候我们就用巧取得方式来获取,方法如下:

     /// 截屏
    ///
    /// - Parameters:
    ///   - view: 要截屏的view
    /// - Returns: 一个UIImage
    func cutFullImageWithView(scrollView:UIScrollView) -> UIImage
    {
        // 记录当前的scrollView的偏移量和坐标
        let currentContentOffSet:CGPoint = scrollView.contentOffset
        let currentFrame:CGRect = scrollView.frame;
        
        // 设置为zero和相应的坐标
        scrollView.contentOffset = CGPoint.zero
        scrollView.frame = CGRect.init(x: 0, y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height)
        
        // 参数①:截屏区域  参数②:是否透明  参数③:清晰度
        UIGraphicsBeginImageContextWithOptions(scrollView.contentSize, true, UIScreen.main.scale)
        scrollView.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        
        // 重新设置原来的参数
        scrollView.contentOffset = currentContentOffSet
        scrollView.frame = currentFrame
        
        UIGraphicsEndImageContext();
        
        return image;
    }

这里是保证他是scrllView,来切换相应的offset和frame,来截取屏幕。有一点要注意,比如你的是tableView,下面的数据中的图片没有加载出来,也是肯定不会显示的。
接下来就是把截图保存到相册,下面是保存到系统相册:

    func writeImageToAlbum(image:UIImage)
    {
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(image:didFinishSavingWithError:contextInfo:)), nil)
    }
    
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafeRawPointer)
    {
        if let e = error as NSError?
        {
            print(e)
        }
        else
        {
            UIAlertController.init(title: nil,
                                   message: "保存成功!",
                                   preferredStyle: UIAlertControllerStyle.alert).show(self, sender: nil);
        }
    }

写入到指定的相册,这里看到的是先写入相册,再移动到指定的相册

       // 看有没有指定的相册
        let library = ALAssetsLibrary.init()
        let albumGroups = NSMutableArray()
        
        library.enumerateGroups(withTypes: ALAssetsGroupType(ALAssetsGroupAll), using:
            {
                oneGroup,pointer in
                albumGroups.add(oneGroup! as ALAssetsGroup)
        },
                                failureBlock:
            {
                error in
        })
        
        var haveCustomAlbum = false
        for albumGroup in albumGroups
        {
            let groupName:String = (albumGroup as! ALAssetsGroup).value(forProperty: ALAssetsGroupPropertyName) as! String
            print(groupName)
            if groupName == "指定相册"
            {
                haveCustomAlbum = true
            }
        }

如果有指定相册直接写入没有就去创建

// 这里是创建相册
if !haveCustomAlbum
        {
            library.addAssetsGroupAlbum(withName: "指定相册",
                                        resultBlock:
                {alAsetGroup in
                    if alAsetGroup != nil
                    {
                        print("创建相册成功");
                    }
            },
                                        failureBlock:
                {error in
                    print("创建相册失败");
            })
        }

下面是写入到指定的相册,下面的image,group和library都是上面获取到的

func writeImageToCustomAlbumFinish(image:UIImage,library:ALAssetsLibrary,alAsetGroup:ALAssetsGroup)
    {
        // 首先写入到写到相册 这里也可以用PHPhotoLibrary来做
        library.writeImage(toSavedPhotosAlbum: image.cgImage, orientation:.up, completionBlock:
            { url,error in
                if (error != nil)
                {
                    // 取到asset
                    library.asset(for: url, resultBlock:
                        {
                            aAlAset in
                            if aAlAset != nil
                            {
                                // 添加到group
                                alAsetGroup.add(aAlAset)
                            }
                    },
                                  failureBlock:
                        {
                            error in
                    })
                }
        })
    }

拼图

func combinTwoImage(image1:UIImage,image2:UIImage) -> UIImage
    {
        let width = max(image1.size.width, image2.size.width)
        let height = image1.size.height + image2.size.height
        let offScreenSize = CGSize.init(width: width, height: height)
        
        UIGraphicsBeginImageContext(offScreenSize);
        
        let rect = CGRect.init(x:0, y:0, width:width, height:image1.size.height)
        image1.draw(in: rect)
        
        let rect2 = CGRect.init(x:0, y:image1.size.height, width:width, height:image2.size.height)
        image1.draw(in: rect2)
        
        let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        
        UIGraphicsEndImageContext();
        
        return image;
    }

你可能感兴趣的:(Swift/iOS - 截屏,长屏,拼图,保存图片到指定的相册)