gpt4 book ai didi

swift - 在 CGContext 中重新创建 UIImageView 的 CGAffineTransform

转载 作者:行者123 更新时间:2023-11-30 11:10:35 25 4
gpt4 key购买 nike

我在 UIVIew 中使用 clipsToBounds = true 转换了 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(因此没有比例)时,此功能才有效。否则,我无法获得正确的图像。这是一个屏幕截图,以便您查看:

enter image description here

这不一样。很难弄清楚如何正确地转换上下文,我不完全理解它。有什么想法吗?

谢谢!

最佳答案

这是一个谜。我真的花了几个小时试图把这件事做好。发布这个问题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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com