在CGContext中重新创建UIImageView的CGAffineTransform

问题描述 投票:0回答:1

我在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(因此没有比例)时才有效。否则,我没有得到正确的图像。这是一个截图,以便您看到它:

enter image description here

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

谢谢!

swift image core-graphics cgaffinetransform
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()
© www.soinside.com 2019 - 2024. All rights reserved.