我已经创建了这个类的Swift版本:https://github.com/bennythemink/ZoomRotatePanImageView/blob/master/ZoomRotatePanImageView.m效果很好。现在我想将修改后的图像保存到文件中。问题是我想以全分辨率保存它,而且我想保存只对用户可见的区域。
让我举个简单的例子:
这就是它在我的应用中的外观。图像是iOS模拟器中的一些示例。大多数是在屏幕外。我只想看到可见的部分。
保存而不裁剪后,它看起来像这样:
到目前为止,剪掉它之后很好。
但现在让我们做一些改变:
保存后:
看起来它被错误的支点所改变。我该如何解决?
这是我的保存代码:
UIGraphicsBeginImageContextWithOptions(image.size, false, 0)
let context = UIGraphicsGetCurrentContext()
let transform = imageView.transform
let imageRect = CGRectMake(0, 0, image.size.width, image.size.height)
CGContextSetFillColorWithColor(context, UIColor.blueColor().CGColor) //for debugging
CGContextFillRect(context, imageRect)
CGContextConcatCTM(context, transform)
image.drawInRect(imageRect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
有一种更简单的方法来实现它:
UIGraphicsBeginImageContextWithOptions(imageContainer.bounds.size, false, 0)
self.imageContainer.drawViewHierarchyInRect(imageContainer.bounds, afterScreenUpdates: true)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
然而,输出图像的视图大小不是实际图像,我想要它以全分辨率。
答案 0 :(得分:4)
更新了可处理任何尺寸图像的代码:
let boundsScale = imageView.bounds.size.width / imageView.bounds.size.height
let imageScale = image!.size.width / image!.size.height
let size = (image?.size)!
var canvasSize = size
if boundsScale > imageScale {
canvasSize.width = canvasSize.height * boundsScale
}else{
canvasSize.height = canvasSize.width / boundsScale
}
let xScale = canvasSize.width / imageView.bounds.width
let yScale = canvasSize.height / imageView.bounds.height
let center = CGPointApplyAffineTransform(imageView.center, CGAffineTransformScale(CGAffineTransformIdentity, xScale, yScale))
let xCenter = center.x
let yCenter = center.y
UIGraphicsBeginImageContextWithOptions(canvasSize, false, 0);
let context = UIGraphicsGetCurrentContext()!
//Apply transformation
CGContextTranslateCTM(context, xCenter, yCenter)
CGContextConcatCTM(context, imageView.transform)
CGContextTranslateCTM(context, -xCenter, -yCenter)
var drawingRect : CGRect = CGRectZero
drawingRect.size = canvasSize
//Transaltion
drawingRect.origin.x = (xCenter - size.width*0.5)
drawingRect.origin.y = (yCenter - size.height*0.5)
//Aspectfit calculation
if boundsScale > imageScale {
drawingRect.size.width = drawingRect.size.height * imageScale
}else{
drawingRect.size.height = drawingRect.size.width / imageScale
}
image!.drawInRect(drawingRect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()