我已经创建了这个类的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()
Run Code Online (Sandbox Code Playgroud)
有一种更简单的方法来实现它:
UIGraphicsBeginImageContextWithOptions(imageContainer.bounds.size, false, 0)
self.imageContainer.drawViewHierarchyInRect(imageContainer.bounds, afterScreenUpdates: true)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
Run Code Online (Sandbox Code Playgroud)
但是输出图像的视图大小不是实际图像,我希望它以全分辨率.
更新了代码以处理任何大小的图像:
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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1025 次 |
| 最近记录: |