У меня есть преобразованный UIImage
внутри UIVIew
с clipsToBounds = true
, и я хочу воссоздать (перерисовать) его точно, используя 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 (поэтому без масштаба). В противном случае я не получу правильное изображение. Вот скриншот, чтобы вы могли его увидеть:
Это не то же самое. Трудно понять, как правильно трансформировать контекст, я не совсем понимаю. Есть идеи?
Спасибо!