我在具有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(因此没有刻度)时,此方法才起作用。否则,我将无法获得正确的图像。这是一个屏幕截图,您可以看到它:这是不一样的。很难弄清楚如何正确地转换上下文,我并不完全理解它。有任何想法吗?
谢谢!
最佳答案
这是一个谜。我确实花了几个小时试图做到这一点。发布此问题后5分钟,我解决了问题。如果您绘制它,实际上并不难(我用photoshop可视化了坐标系并进行了一些操作。应该早些做。)
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()!
context.concatenate(CGAffineTransform.identity.scaledBy(x: scale, y: scale).translatedBy(x: size.width / (2 * scale), y: size.height / (2 * scale)).translatedBy(x: offset.x / scale, y: offset.y / scale))
image.draw(in: CGRect(x: -image.size.width / 2, y: -image.size.height / 2, width: image.size.width, height: image.size.height))
bottomImageView.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
关于swift - 在CGContext中重新创建UIImageView的CGAffineTransform,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52220044/