Aashay
Aashay

Reputation: 383

How to convert only some of the subviews of a UIView to UIImage

I have been stuck on this since yesterday. I am trying to capture only some of the subviews of a UIView. This main UIView has 4 subviews namely, the header, the caption, the image, and the footer. I am trying to capture the caption and the image only.

I have tried to use UIGraphicsBeginImageContextWithOptions() and setting the CGSize from the y coordinate of the caption to the height of the image. But, it still doesn't capture only the caption and the image.

I also tried using a UIStackView, here, I am able to capture the caption and the image only but the stackview itself still remains the size of the main UIView. I can fix the sizing issue but the main issue I'm having using UIStackView is that when I use addArrangedSubview:, the subview being added disappears from the main UIView.

I'm confused about how to go about doing this? Using just UIGraphicsBeginImageContextWithOptions() doesn't allow me to capture only the caption and the image and using the UIStackView makes the caption and the image disappear from the main UIView.

I hope this explanation hasn't been confusing and I'll be happy to clear someone's doubts.

Please advice me about the best way I can capture only some of the subviews from the main UIView.

Any help is appreciated!

Thanks a lot in advance!

Edit: Method that worked for me, thanks to PaulDaPigeon's comments. I ended up using UIGraphicsBeginImageContextWithOptions().

- (UIImage *) extractImageOfSubviewFromView: (UIView *)view {

  CGRect finalImageRect = CGRectMake(0, 0, view.frame.size.width, (view.lblCaption.frame.size.height + view.image.frame.size.height));

  UIGraphicsBeginImageContextWithOptions(finalImageRect, NO, 0.0);
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGContextTranslateCTM(finalImageRect, 0, - view.header.frame.size.height);
  [view.layer renderInContext:context];

  UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  return finalImage;

}

Hope this helps someone in the future!

Upvotes: 0

Views: 300

Answers (1)

PaulDaPigeon
PaulDaPigeon

Reputation: 303

The right way to do this seems to be with UIGraphicsBeginImageContextWithOptions() but instead of adding the view itself you should try [stackView addArrangedSubview:subview.copy]; to avoid removing it from the main view.

Upvotes: 1

Related Questions