Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

ios - Subview UIImage disappears on UIImageView

I have a UIImageView which has another added UIImageView on top as subview, seen below:

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)

set in viewDidLoad and i can see it nicely on the screen. But later on, when i access this self.imageView to share it, i only see original image without subview, seen below.

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

Please help me, what could be the cause and what can overcome this issue? I appreciate it all.

question from:https://stackoverflow.com/questions/65902962/subview-uiimage-disappears-on-uiimageview

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Adding as subview does not mean two images are merged. For this, you need to first merge two images or need to take a screenshot of this image view.

Like this taking screenshot: (Note: Image size is dependent on image view size, for the original size you need to calculate frame according to the requirement.)

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...
}

Edit Or you can merge two images with the original size. Like this

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...
}

See more for combine/merge 2 images: here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...