【发布时间】:2018-09-07 09:56:16
【问题描述】:
我在带有clipsToBounds = true 的UIVIew 中有一个转换后的UIImage,我想使用CGContext 重新创建(重绘)它。很难解释,代码如下:
class ViewController: UIViewController {
@IBOutlet weak var topView: UIView!
@IBOutlet weak var topImageView: UIImageView!
@IBOutlet weak var bottomImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// the example image
let image = UIImage(named: "image")!
// topImageView is embedded inside topView so that the image is being clipped
topView.clipsToBounds = true
topImageView.image = image
topImageView.contentMode = .center // I set this to center because it seems to be easier to draw it then
// The transformation data
let size = CGSize(width: 800, height: 200)
let scale: CGFloat = 1.5
let offset: (x: CGFloat, y: CGFloat) = (x: 0.0, y: 0.0)
// transform the imageView
topImageView.transform = CGAffineTransform(translationX: offset.x, y: offset.y).scaledBy(x: scale, y: scale)
// Now try to recreate the transform by using a transformed CGContext
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()!
// transform the context
// Almost the same as above, but I additionally move the context so that the middle of the image is in the middle of the size defined above
context.concatenate(CGAffineTransform(translationX: (-image.size.width / 2 + size.width / 2) + offset.x, y: (-image.size.height / 2 + size.height / 2) + offset.y).scaledBy(x: scale, y: scale))
image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
bottomImageView.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
}
这仅在我将scale 设置为 1.0(因此没有比例)时才有效。否则,我没有得到正确的图像。这是一个屏幕截图,以便您查看:
不一样。很难弄清楚如何正确转换上下文,我不完全理解。有什么想法吗?
谢谢!
【问题讨论】:
标签: swift image core-graphics cgaffinetransform