guard let ciImage = self.imageViewOut.image?.ciImage else { return } guard let imageSize = self.imageViewOut.image?.size else { return } let frameSize = self.scrollView.frame.size let ciContext = CIContext(options: nil) let zoomScale = self.scrollView.zoomScale // ズームしない場合、contentSizeがセットれさず、ゼロのまま。 // そこで、frameSizeと、zoomScaleから contentSizeを計算する。 // let contentSize = self.scrollView.contentSize let contentSize = CGSize(width: frameSize.width * zoomScale, height: frameSize.height * zoomScale) let contentOffset = self.scrollView.contentOffset let x = contentOffset.x * imageSize.width / contentSize.width let y1 = contentSize.height - contentOffset.y - frameSize.height let y2 = imageSize.height / contentSize.height let y = y1 * y2 let newOffset = CGPoint(x: x, y: y) let newSize = CGSize(width: imageSize.width/zoomScale, height: imageSize.height/zoomScale) let newExtent = CGRect(origin: newOffset, size: newSize) let cgImage = ciContext.createCGImage(ciImage, from: newExtent) let uiImageToSave = UIImage(cgImage: cgImage!, scale: 1.0, orientation: .up) UIImageWriteToSavedPhotosAlbum(uiImageToSave, self, #selector(didFinishSavingImage), nil)