子视图 UIImage 在 UIImageView 上消失

Subview UIImage disappears on UIImageView

我有一个 UIImageView,它在顶部添加了另一个 UIImageView 作为子视图,如下所示:

self.imageView.image = UIImage(named: "original_image.png")

let demoStampImage = UIImage(named: "demo_stamp.png")
let frame = CGRect(x: (UIScreen.main.bounds.width / 2) - 50, y: (UIScreen.main.bounds.height / 2) - 50, width: 100, height: 100)
let demoStampImageView = UIImageView(image: demoStampImage)
demoStampImageView.frame = frame
    
self.imageView.addSubview(demoStampImageView)

设置在 viewDidLoad 中,我可以在屏幕上清楚地看到它。但是后来,当我访问这个 self.imageView 来分享它时,我只看到没有子视图的原始图像,如下所示。

@objc func shareIt() {
  let imageToShare = [ self.imageView.image ] -> Here image has no subview
  //Code goes on...
}

请帮帮我,可能是什么原因,有什么办法可以解决这个问题?我很感激这一切。

添加为子视图并不意味着合并了两个图像。为此,您需要先合并两张图片或需要截取此图片视图的屏幕截图。

像这样截图:(注意:图片尺寸取决于图片视图尺寸,原始尺寸需要根据要求计算帧数。)

extension UIView {
    func snapImage() -> UIImage {
        return UIGraphicsImageRenderer(size: bounds.size).image { _ in
            drawHierarchy(in: CGRect(origin: .zero, size: bounds.size), afterScreenUpdates: true)
        }
    }
}

@objc func shareIt() {
  let imageToShare = [ self.imageView.snapImage() ]
  //Code goes on...
}

编辑 或者您可以将两个图像合并为原始大小。像这样

extension UIImage {
    func mearge(image: UIImage) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
        
        self.draw(in: CGRect(x:0 , y: 0, width: size.width, height: size.height))
        let topImageFrame = CGRect(x: (size.width / 2) - 50, y: (size.height / 2) - 50, width: 100, height: 100)
        image.draw(in: topImageFrame)
        
        let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        
        return newImage
    }
}


@objc func shareIt() {
    let imageToShare = [ self.imageView.image!.mearge(image:demoStampImage!) ]
  //Code goes on...
}

查看 combine/merge 2 张图片的更多信息:here

self.imageView = UIImageView()
self.imageView.image = UIImage(named: "original_image.png")

let demoStampImage = UIImage(named: "demo_stamp.png")
let frame = CGRect(x: (UIScreen.main.bounds.width / 2) - 50, y: (UIScreen.main.bounds.height / 2) - 50, width: 100, height: 100)
let demoStampImageView = UIImageView(image: demoStampImage)
demoStampImageView.tag = 1 //Define tag to find it later
demoStampImageView.frame = frame
    
self.imageView.addSubview(demoStampImageView)
let imageViewSubviews = self.imageView.subviews.filter{[=11=].tag == 1}
let demoStampImageView = imageViewSubviews[0] as! UIImageView//This is the only view with tag == 1
let demoImage = demoStampImageView.image

请理解我在没有错误处理的情况下将类型大小写强制为 UIImageView。这应该可行,但强制执行任何操作都有潜在的失败并可能导致问题。